﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FIFP.Common;
using FIFP.DashBoard.Helper;
using System.Collections.Generic;
using Telerik.Windows.Controls.ScheduleView;
using FIFP.DashBoard.Model;
using Telerik.Windows.Controls;
using System.Linq;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using FIFP.DashBoard.Views;
using FIFP.DashBoard.Converters;
using System.Linq.Expressions;
using System.Collections;
using System.Threading;
using FIFP.DashBoard.RelationalDataService;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using Telerik.Windows;
using FIFP.DashBoard.Calculation;
using System.Windows.Messaging;
using System.Windows.Browser;
using System.Xml.Serialization;
using System.Text;
using Telerik.Windows.Controls.Charting;
using System.ServiceModel;
using System.Text.RegularExpressions;

namespace FIFP.DashBoard.ViewModel
{
    public class ImportVM : ViewModelCore, INotifyPropertyChanged, INotifyDataErrorInfo
    {
        #region Variables
        public event EventHandler<CustomEventArgs<AppointmentGroup>> OnAppointmentDataCompleted;
        public event EventHandler<CustomEventArgs<List<string>>> OnDivisionListDataCompleted;
        public event EventHandler OnUnitNameListDataCompleted;
        private readonly ICollection<ValidationResult> _validationResults;
        CreateScenarioPopup scenarioPopup;
        ECPopup ecPopup;
        AddActivityPopup activityPopup;
        //private RelationalDataServiceClient queryClient = null;
        private int newactivityId = 0;
        private NewCalculation calculation = new NewCalculation();
        private bool isLoadingUnitCapacityCompleted = false;
        private bool isLoadingUnitLayerCompleted = false;
        LocalMessageSender localMessageECSender;
        LocalMessageReceiver localMessageECReceiver;
        LocalMessageSender localMessageMCSender;
        LocalMessageReceiver localMessageMCReceiver;

        string strECSender;
        string strECReceiver;
        string strMCSender;
        string strMCReceiver;

        private string retXml = string.Empty;
        #endregion

        #region Properties
        private List<Scenario> currentUserScenarioList = new List<Scenario>();
        public List<Scenario> CurrentUserScenarioList
        {
            get { return currentUserScenarioList; }
            set { SetPropertyValue(() => CurrentUserScenarioList, value, val => currentUserScenarioList = val); }
        }

        private Dictionary<string, double> unitCapacityDictionary = new Dictionary<string, double>();
        public Dictionary<string, double> UnitCapacityDictionary
        {
            get { return unitCapacityDictionary; }
            set { unitCapacityDictionary = value; }
        }

        //Input : unit layer relationship
        private Dictionary<string, List<UnitLayer>> layerUnitsDictionary = new Dictionary<string, List<UnitLayer>>();
        public Dictionary<string, List<UnitLayer>> LayerUnitsDictionary
        {
            get { return layerUnitsDictionary; }
            set { layerUnitsDictionary = value; }
        }

        private List<string> divisionList = new List<string>();
        public List<string> DivisionList
        {
            get { return divisionList; }
            set { SetPropertyValue(() => DivisionList, value, val => divisionList = val); }
        }

        private List<Unit> unitNameList = new List<Unit>();
        public List<Unit> UnitNameList
        {
            get { return unitNameList; }
            set { SetPropertyValue(() => UnitNameList, value, val => unitNameList = val); }
        }

        private List<Unit> settingsUnitNameList = new List<Unit>();
        public List<Unit> SettingsUnitNameList
        {
            get { return settingsUnitNameList; }
            set { SetPropertyValue(() => SettingsUnitNameList, value, val => settingsUnitNameList = val); }
        }

        private List<string> unitTypeList = new List<string>();
        public List<string> UnitTypeList
        {
            get { return unitTypeList; }
            set { SetPropertyValue(() => UnitTypeList, value, val => unitTypeList = val); }
        }

        private List<string> sourceUnitTypeList = new List<string>();
        public List<string> SourceUnitTypeList
        {
            get { return sourceUnitTypeList; }
            set { SetPropertyValue(() => SourceUnitTypeList, value, val => sourceUnitTypeList = val); }
        }


        private List<string> settingsUnitTypeList = new List<string>();
        public List<string> SettingsUnitTypeList
        {
            get { return settingsUnitTypeList; }
            set { SetPropertyValue(() => SettingsUnitTypeList, value, val => settingsUnitTypeList = val); }
        }

        private List<ActivityType> activityCodeList = new List<ActivityType>();
        public List<ActivityType> ActivityCodeList
        {
            get { return activityCodeList; }
            set { SetPropertyValue(() => ActivityCodeList, value, val => activityCodeList = val); }
        }

        private List<ActivityType> divisionCodeList = new List<ActivityType>();
        public List<ActivityType> DivisionCodeList
        {
            get { return divisionCodeList; }
            set { SetPropertyValue(() => DivisionCodeList, value, val => divisionCodeList = val); }
        }

        private Style _OpenRawDataStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
        public Style OpenRawDataStyle
        {
            get { return _OpenRawDataStyle; }
            set { SetPropertyValue(() => OpenRawDataStyle, value, val => _OpenRawDataStyle = val); }
        }

        private Style _OpenBaseScenarioStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
        public Style OpenBaseScenarioStyle
        {
            get { return _OpenBaseScenarioStyle; }
            set { SetPropertyValue(() => OpenBaseScenarioStyle, value, val => _OpenBaseScenarioStyle = val); }
        }

        private Style _ScenarioStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
        public Style ScenarioStyle
        {
            get { return _ScenarioStyle; }
            set { SetPropertyValue(() => ScenarioStyle, value, val => _ScenarioStyle = val); }
        }

        private Style _SaveAsStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
        public Style SaveAsStyle
        {
            get { return _SaveAsStyle; }
            set { SetPropertyValue(() => SaveAsStyle, value, val => _SaveAsStyle = val); }
        }

        private Style _SaveStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
        public Style SaveStyle
        {
            get { return _SaveStyle; }
            set { SetPropertyValue(() => SaveStyle, value, val => _SaveStyle = val); }
        }

        private List<FIFPAppointment> importPlans = new List<FIFPAppointment>();
        public List<FIFPAppointment> ImportPlans
        {
            get { return importPlans; }
            set
            {
                if (importPlans != value)
                {
                    importPlans = value;
                    NotifyPropertyChanged(() => ImportPlans);
                }
            }
            //set { SetPropertyValue(() => ImportPlans, value, val => importPlans = val); }
        }

        private List<FIFPAppointment> scenarioPlans = new List<FIFPAppointment>();
        public List<FIFPAppointment> ScenarioPlans
        {
            get { return scenarioPlans; }
            set
            {
                if (scenarioPlans != value)
                {
                    scenarioPlans = value;
                    NotifyPropertyChanged(() => ScenarioPlans);
                }
            }
            //set { SetPropertyValue(() => ScenarioPlans, value, val => scenarioPlans = val); }
        }

        private Dictionary<int, FIFPAppointment> originalPlansDictionary = new Dictionary<int, FIFPAppointment>();
        public Dictionary<int, FIFPAppointment> OriginalPlansDictionary
        {
            get { return originalPlansDictionary; }
            set { SetPropertyValue(() => OriginalPlansDictionary, value, val => originalPlansDictionary = val); }
        }

        private bool isBaseScenario = false;
        public bool IsBaseScenario
        {
            get { return isBaseScenario; }
            set { SetPropertyValue(() => IsBaseScenario, value, val => isBaseScenario = val); }
        }

        private bool isScenarioExist = false;
        public bool IsScenarioExist
        {
            get { return isScenarioExist; }
            set { SetPropertyValue(() => IsScenarioExist, value, val => isScenarioExist = val); }
        }

        private string _ScenarioName = string.Empty;
        [Display(Name = FIFPConstants.DISPLAY_SCENARIO)]
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_SCENARIO)]
        public string ScenarioName
        {
            get { return _ScenarioName; }
            set
            {
                if (_ScenarioName != value)
                {
                    _ScenarioName = value;
                    OnPropertyChanged(() => this._ScenarioName);
                }
            }
        }

        private List<Scenario> scenarioList = new List<Scenario>();
        public List<Scenario> ScenarioList
        {
            get { return scenarioList; }
            set { SetPropertyValue(() => ScenarioList, value, val => scenarioList = val); }
        }

        private Scenario currentScenario = new Scenario();
        public Scenario CurrentScenario
        {
            get { return currentScenario; }
            set { SetPropertyValue(() => CurrentScenario, value, val => currentScenario = val); }
        }

        private int selectedScenarioId;
        public int SelectedScenarioId
        {
            get { return selectedScenarioId; }
            set { SetPropertyValue(() => SelectedScenarioId, value, val => selectedScenarioId = val); }
        }

        private Visibility _FilterVisibility = Visibility.Collapsed;
        public Visibility FilterVisibility
        {
            get { return _FilterVisibility; }
            set { SetPropertyValue(() => FilterVisibility, value, val => _FilterVisibility = val); }
        }
        private Visibility _IsUnitFilterVisibility = Visibility.Visible;
        public Visibility IsUnitFilterVisibility
        {
            get { return _IsUnitFilterVisibility; }
            set { SetPropertyValue(() => IsUnitFilterVisibility, value, val => _IsUnitFilterVisibility = val); }
        }

        private Visibility _FilterTreeVisibility = Visibility.Collapsed;
        public Visibility FilterTreeVisibility
        {
            get { return _FilterTreeVisibility; }
            set { SetPropertyValue(() => FilterTreeVisibility, value, val => _FilterTreeVisibility = val); }
        }

        private string _UnitName = string.Empty;
        [Display(Name = FIFPConstants.DISPLAY_UNITNAME)]
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_UNITNAME)]
        public string UnitName
        {
            get { return _UnitName; }
            set
            {
                if (_UnitName != value)
                {
                    _UnitName = value;
                    NotifyPropertyChanged(() => UnitName);
                }
            }
        }

        private bool isUnitNameExist = false;
        public bool IsUnitNameExist
        {
            get { return isUnitNameExist; }
            set { SetPropertyValue(() => IsUnitNameExist, value, val => isUnitNameExist = val); }
        }

        private bool _IsFilterButtonEnabled = false;
        public bool IsFilterButtonEnabled
        {
            get { return _IsFilterButtonEnabled; }
            set { SetPropertyValue(() => IsFilterButtonEnabled, value, val => _IsFilterButtonEnabled = val); }
        }

        private List<Unit> unitList = new List<Unit>();
        public List<Unit> UnitList
        {
            get { return unitList; }
            set { SetPropertyValue(() => UnitList, value, val => unitList = val); }
        }

        private List<Unit> treeViewUnitList = new List<Unit>();
        public List<Unit> TreeViewUnitList
        {
            get { return treeViewUnitList; }
            set { SetPropertyValue(() => TreeViewUnitList, value, val => treeViewUnitList = val); }
        }

        private List<FIFPAppointment> linkedShutdownList = new List<FIFPAppointment>();
        public List<FIFPAppointment> LinkedShutdownList
        {
            get { return linkedShutdownList; }
            set { SetPropertyValue(() => LinkedShutdownList, value, val => linkedShutdownList = val); }
        }

        private List<int> childUnitList = new List<int>();
        public List<int> ChildUnitList
        {
            get { return childUnitList; }
            set { SetPropertyValue(() => ChildUnitList, value, val => childUnitList = val); }
        }

        private ObservableCollection<MenuItem> openMenuItems = new ObservableCollection<MenuItem>();
        public ObservableCollection<MenuItem> OpenMenuItems
        {
            get { return openMenuItems; }
            set { SetPropertyValue(() => OpenMenuItems, value, val => openMenuItems = val); }
        }

        private ObservableCollection<MenuItem> saveMenuItems = new ObservableCollection<MenuItem>();
        public ObservableCollection<MenuItem> SaveMenuItems
        {
            get { return saveMenuItems; }
            set { SetPropertyValue(() => SaveMenuItems, value, val => saveMenuItems = val); }
        }

        private Unit selectedActivityUnit;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_COMBOUNITNAME)]
        public Unit SelectedActivityUnit
        {
            get { return selectedActivityUnit; }
            set
            {
                if (value == null)
                    return;
                selectedActivityUnit = value;
                NotifyPropertyChanged(() => SelectedActivityUnit);
            }
        }

        private Unit settingsSelectedActivityUnit;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_COMBOUNITNAME)]
        public Unit SettingsSelectedActivityUnit
        {
            get { return settingsSelectedActivityUnit; }
            set
            {
                if (value == null)
                    return;
                settingsSelectedActivityUnit = value;
                NotifyPropertyChanged(() => SettingsSelectedActivityUnit);
            }
        }


        private string selectedUnitType;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_UNIT_TYPE)]
        public string SelectedUnitType
        {
            get { return selectedUnitType; }
            set
            {
                if (value == null)
                    return;
                selectedUnitType = value;
                NotifyPropertyChanged(() => SelectedUnitType);
            }
        }

        private string settingsSelectedUnitType;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_UNIT_TYPE)]
        public string SettingsSelectedUnitType
        {
            get { return settingsSelectedUnitType; }
            set
            {
                if (value == null)
                    return;
                settingsSelectedUnitType = value;
                NotifyPropertyChanged(() => SettingsSelectedUnitType);
            }
        }

        private ActivityType selectedActivityCode;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_ACTIVITY)]
        public ActivityType SelectedActivityCode
        {
            get { return selectedActivityCode; }
            set
            {
                if (value == null)
                    return;
                selectedActivityCode = value;
                NotifyPropertyChanged(() => SelectedActivityCode);
            }
        }

        private ActivityType selectedDivisionName;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_DIVISION)]
        public ActivityType SelectedDivisionName
        {
            get { return selectedDivisionName; }
            set
            {
                if (value == null)
                    return;
                selectedDivisionName = value;
                NotifyPropertyChanged(() => SelectedDivisionName);
            }
        }

        private Layer selectedLayer;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_LAYER)]
        public Layer SelectedLayer
        {
            get { return selectedLayer; }
            set
            {
                if (value == null)
                    return;
                selectedLayer = value;
                NotifyPropertyChanged(() => SelectedLayer);
            }
        }

        private Layer selectedMaxProdLayer;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_LAYER)]
        public Layer SelectedMaxProdLayer
        {
            get { return selectedMaxProdLayer; }
            set
            {
                if (value == null)
                    return;
                selectedMaxProdLayer = value;
                NotifyPropertyChanged(() => SelectedMaxProdLayer);
            }
        }


        private bool _BValidate = false;
        public bool BValidate
        {
            get { return _BValidate; }
            set { SetPropertyValue(() => BValidate, value, val => _BValidate = val); }
        }

        private bool _BPercentageValidate = false;
        public bool BPercentageValidate
        {
            get { return _BPercentageValidate; }
            set { SetPropertyValue(() => BPercentageValidate, value, val => _BPercentageValidate = val); }
        }

        private bool isUnitNameEnabled = false;
        public bool IsUnitNameEnabled
        {
            get { return isUnitNameEnabled; }
            set { SetPropertyValue(() => IsUnitNameEnabled, value, val => isUnitNameEnabled = val); }
        }

        private bool isUnitTypeEnabled = false;
        public bool IsUnitTypeEnabled
        {
            get { return isUnitTypeEnabled; }
            set { SetPropertyValue(() => IsUnitTypeEnabled, value, val => isUnitTypeEnabled = val); }
        }

        private bool isActivityCodeEnabled = false;
        public bool IsActivityCodeEnabled
        {
            get { return isActivityCodeEnabled; }
            set { SetPropertyValue(() => IsActivityCodeEnabled, value, val => isActivityCodeEnabled = val); }
        }


        private DateTime activityStartDate = DateTime.Now;
        [Display(Name = FIFPConstants.DISPLAY_ACTIVITY_STARTDATE)]
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_ACTIVITY_STARTDATE)]
        public DateTime ActivityStartDate
        {
            get { return activityStartDate; }
            set
            {
                if (value != null)
                    activityStartDate = new DateTime(value.Year, value.Month, value.Day, 0, 0, 0);
                NotifyPropertyChanged(() => ActivityStartDate);
                NotifyPropertyChanged(() => ActivityEndDate);
            }
        }
        private DateTime activityEndDate = DateTime.Now.AddDays(1);
        [Display(Name = FIFPConstants.DISPLAY_ACTIVITY_ENDDATE)]
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_ACTIVITY_ENDATE)]
        public DateTime ActivityEndDate
        {
            get { return activityEndDate; }
            set
            {
                if (value != null)
                    activityEndDate = new DateTime(value.Year, value.Month, value.Day, 23, 59, 59);
                NotifyPropertyChanged(() => ActivityEndDate);
                NotifyPropertyChanged(() => ActivityStartDate);
            }
        }
        private string activityDesc;
        public string ActivityDesc
        {
            get { return activityDesc; }
            set { SetPropertyValue(() => ActivityDesc, value, val => activityDesc = val); }
        }

        private string _CommentsText;
        public string CommentsText
        {
            get { return _CommentsText; }
            set { SetPropertyValue(() => CommentsText, value, val => _CommentsText = val); }
        }


        private int currentScenarioId;
        public int CurrentScenarioId
        {
            get { return currentScenarioId; }
            set { SetPropertyValue(() => CurrentScenarioId, value, val => currentScenarioId = val); }
        }

        private string currentScenarioName;
        public string CurrentScenarioName
        {
            get { return currentScenarioName; }
            set { SetPropertyValue(() => CurrentScenarioName, value, val => currentScenarioName = val); }
        }

        private List<string> monthList = new List<string>() { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
        public List<string> MonthList
        {
            get { return monthList; }
            set { SetPropertyValue(() => MonthList, value, val => monthList = val); }
        }

        private List<int> yearList = new List<int>();
        public List<int> YearList
        {
            get { return yearList; }
            set { SetPropertyValue(() => YearList, value, val => yearList = val); }
        }

        private string selectedMonth = string.Empty;
        public string SelectedMonth
        {
            get { return selectedMonth; }
            set { SetPropertyValue(() => SelectedMonth, value, val => selectedMonth = val); }
        }

        private int selectedYear;
        public int SelectedYear
        {
            get { return selectedYear; }
            set { SetPropertyValue(() => SelectedYear, value, val => selectedYear = val); }
        }
        private Visibility monthComboVisibility = Visibility.Collapsed;
        public Visibility MonthComboVisibility
        {
            get { return monthComboVisibility; }
            set { SetPropertyValue(() => MonthComboVisibility, value, val => monthComboVisibility = val); }
        }
        private string selectedECPlan = string.Empty;
        public string SelectedECPlan
        {
            get { return selectedECPlan; }
            set { SetPropertyValue(() => SelectedECPlan, value, val => selectedECPlan = val); }
        }
        private bool isAddActivityButtonEnabled = false;
        public bool IsAddActivityButtonEnabled
        {
            get { return isAddActivityButtonEnabled; }
            set { SetPropertyValue(() => IsAddActivityButtonEnabled, value, val => isAddActivityButtonEnabled = val); }
        }

        private bool isAddButtonEnabled = true;
        public bool IsAddButtonEnabled
        {
            get { return isAddButtonEnabled; }
            set { SetPropertyValue(() => IsAddButtonEnabled, value, val => isAddButtonEnabled = val); }
        }

        private bool isCalButtonEnabled = false;
        public bool IsCalButtonEnabled
        {
            get { return isCalButtonEnabled; }
            set { SetPropertyValue(() => IsCalButtonEnabled, value, val => isCalButtonEnabled = val); }
        }

        private bool isCalMaxButtonEnabled = false;
        public bool IsCalMaxButtonEnabled
        {
            get { return isCalMaxButtonEnabled; }
            set { SetPropertyValue(() => IsCalMaxButtonEnabled, value, val => isCalMaxButtonEnabled = val); }
        }

        private Visibility calculateMaxVisibility = Visibility.Collapsed;
        public Visibility CalculateMaxVisibility
        {
            get { return calculateMaxVisibility; }
            set { SetPropertyValue(() => CalculateMaxVisibility, value, val => calculateMaxVisibility = val); }
        }

        private bool isUnitCompleted = false;
        public bool IsUnitCompleted
        {
            get { return isUnitCompleted; }
            set { SetPropertyValue(() => IsUnitCompleted, value, val => isUnitCompleted = val); }
        }

        private bool isInitLoadCompleted = false;
        public bool IsInitLoadCompleted
        {
            get { return isInitLoadCompleted; }
            set { SetPropertyValue(() => IsInitLoadCompleted, value, val => isInitLoadCompleted = val); }
        }

        private FIFPGroupUser fifpLoginUserRole;
        public FIFPGroupUser FifpLoginUserRole
        {
            get { return fifpLoginUserRole; }
            set { SetPropertyValue(() => FifpLoginUserRole, value, val => fifpLoginUserRole = val); }
        }

        private List<ActivityType> activityCodeDivisionList = new List<ActivityType>();
        public List<ActivityType> ActivityCodeDivisionList
        {
            get { return activityCodeDivisionList; }
            set { SetPropertyValue(() => ActivityCodeDivisionList, value, val => activityCodeDivisionList = val); }
        }

        private List<ReducedCapacity> reducedCapacityList = new List<ReducedCapacity>();
        public List<ReducedCapacity> ReducedCapacityList
        {
            get { return reducedCapacityList; }
            set { SetPropertyValue(() => ReducedCapacityList, value, val => reducedCapacityList = val); }
        }


        private bool isECBrowserOpened = false;
        public bool IsECBrowserOpened
        {
            get { return isECBrowserOpened; }
            set { SetPropertyValue(() => IsECBrowserOpened, value, val => isECBrowserOpened = val); }
        }

        private bool isMCBrowserOpened = false;
        public bool IsMCBrowserOpened
        {
            get { return isMCBrowserOpened; }
            set { SetPropertyValue(() => IsMCBrowserOpened, value, val => isMCBrowserOpened = val); }
        }

        private List<int> deletedActivityIds = new List<int>();
        public List<int> DeletedActivityIds
        {
            get { return deletedActivityIds; }
            set { SetPropertyValue(() => DeletedActivityIds, value, val => deletedActivityIds = val); }
        }

        private List<RadialSwitch> radialSwitchListFromDB = new List<RadialSwitch>();
        public List<RadialSwitch> RadialSwitchListFromDB
        {
            get { return radialSwitchListFromDB; }
            set { SetPropertyValue(() => RadialSwitchListFromDB, value, val => radialSwitchListFromDB = val); }
        }


        private RadialSwitchHelper radialSwitchDefaultValue;
        public RadialSwitchHelper RadialSwitchDefaultValue
        {
            get { return radialSwitchDefaultValue; }
            set { SetPropertyValue(() => RadialSwitchDefaultValue, value, val => radialSwitchDefaultValue = val); }
        }

        private bool isRCorRadialRequest = false;
        public bool IsRCorRadialRequest
        {
            get { return isRCorRadialRequest; }
            set { SetPropertyValue(() => IsRCorRadialRequest, value, val => isRCorRadialRequest = val); }
        }

        private bool bReloadScenario = false;
        public bool BReloadScenario
        {
            get { return bReloadScenario; }
            set { SetPropertyValue(() => BReloadScenario, value, val => bReloadScenario = val); }
        }

        private bool _BECScanrio = false;
        public bool BECScanrio
        {
            get { return _BECScanrio; }
            set { SetPropertyValue(() => BECScanrio, value, val => _BECScanrio = val); }
        }

        private SettingsData fieldData = new SettingsData();
        public SettingsData FieldData
        {
            get { return fieldData; }
            set
            {
                if (value == null)
                    return;
                fieldData = value;
                NotifyPropertyChanged(() => FieldData);
            }
        }


        private List<Layer> layerList = new List<Layer>();
        public List<Layer> LayerList
        {
            get { return layerList; }
            set { SetPropertyValue(() => LayerList, value, val => layerList = val); }
        }

        private double currentIPR;
        public double CurrentIPR
        {
            get { return currentIPR; }
            set { SetPropertyValue(() => CurrentIPR, value, val => currentIPR = val); }
        }

        private double currentMaxProduction;
        public double CurrentMaxProduction
        {
            get { return currentMaxProduction; }
            set { SetPropertyValue(() => CurrentMaxProduction, value, val => currentMaxProduction = val); }
        }


        private bool isAnimationStarted = false;
        public bool IsAnimationStarted
        {
            get { return isAnimationStarted; }
            set { SetPropertyValue(() => IsAnimationStarted, value, val => isAnimationStarted = val); }

        }
        private double currentCapacity;
        public double CurrentCapacity
        {
            get { return currentCapacity; }
            set { SetPropertyValue(() => CurrentCapacity, value, val => currentCapacity = val); }
        }



        private string newIPR = string.Empty;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_IPR)]
        public string NewIPR
        {
            get { return newIPR; }
            set
            {
                if (NewIPR != value)
                {
                    newIPR = value;
                    NotifyPropertyChanged(() => NewIPR);
                }
            }
        }

        private string newMaxProduction = string.Empty;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_MAXPROD)]
        public string NewMaxProduction
        {
            get { return newMaxProduction; }
            set
            {
                if (NewMaxProduction != value)
                {
                    newMaxProduction = value;
                    NotifyPropertyChanged(() => NewMaxProduction);
                }
            }
        }


        private string newCapacity = string.Empty;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_ISNUMERIC)]
        public string NewCapacity
        {
            get { return newCapacity; }
            set
            {
                if (NewCapacity != value)
                {
                    newCapacity = value;
                    NotifyPropertyChanged(() => NewCapacity);
                }
            }
        }


        private string newMonitoringPercentage = string.Empty;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_PERCENTAGE)]
        public string NewMonitoringPercentage
        {
            get { return newMonitoringPercentage; }
            set
            {
                if (NewMonitoringPercentage != value)
                {
                    newMonitoringPercentage = value;
                    NotifyPropertyChanged(() => NewMonitoringPercentage);
                }
            }
        }

        private string newUnplannedLossesPercentage = string.Empty;
        [CustomValidation(typeof(ErrorValidation), FIFPConstants.VALIDATE_PERCENTAGE)]
        public string NewUnplannedLossesPercentage
        {
            get { return newUnplannedLossesPercentage; }
            set
            {
                if (NewUnplannedLossesPercentage != value)
                {
                    newUnplannedLossesPercentage = value;
                    NotifyPropertyChanged(() => NewUnplannedLossesPercentage);
                }
            }
        }

        private List<Unit> occpRadialFlowList = new List<Unit>();
        public List<Unit> OccpRadialFlowList
        {
            get { return occpRadialFlowList; }
            set { SetPropertyValue(() => OccpRadialFlowList, value, val => occpRadialFlowList = val); }
        }

        private bool isOCCPRadialSwitchSaving = false;
        public bool IsOCCPRadialSwitchSaving
        {
            get { return isOCCPRadialSwitchSaving; }
            set { SetPropertyValue(() => IsOCCPRadialSwitchSaving, value, val => isOCCPRadialSwitchSaving = val); }

        }

        private bool isUnodButtonEnabled = true;
        public bool IsUnodButtonEnabled
        {
            get { return isUnodButtonEnabled; }
            set { SetPropertyValue(() => IsUnodButtonEnabled, value, val => isUnodButtonEnabled = val); }
        }

        private List<FIFPAppointment> scheduleViewAppointments = new List<FIFPAppointment>();
        public List<FIFPAppointment> ScheduleViewAppointments
        {
            get { return scheduleViewAppointments; }
            set { SetPropertyValue(() => ScheduleViewAppointments, value, val => scheduleViewAppointments = val); }
        }


        #endregion

        #region Commands
        private ICommand _CalculateCommand;
        public ICommand CalculateCommand
        {
            get
            {
                return _CalculateCommand ??
                        (_CalculateCommand = new RelayCommand<Button>(Calculate));
            }
        }

        private ICommand _CalculateMaxCommand;
        public ICommand CalculateMaxCommand
        {
            get
            {
                return _CalculateMaxCommand ??
                        (_CalculateMaxCommand = new RelayCommand<Button>(CalculateMaxFieldCapacity));
            }
        }

        private ICommand _UndoCommand;
        public ICommand UndoCommand
        {
            get
            {
                return _UndoCommand ??
                        (_UndoCommand = new RelayCommand<Button>(UndoActivitiesByOneLevelBack));
            }
        }


        private ICommand _ResetPlansEvent;
        public ICommand ResetPlansEvent
        {
            get
            {
                return _ResetPlansEvent ??
                        (_ResetPlansEvent = new RelayCommand<Button>(ShowDefaultPlans));
            }
        }

        private ICommand _ImportPageLoadCommand;
        public ICommand ImportPageLoadCommand
        {
            get
            {
                return _ImportPageLoadCommand ??
                        (_ImportPageLoadCommand = new RelayCommand<Grid>(LoadappointmentsFromDB));
            }
        }

        private ICommand _WarningCommand;
        public ICommand WarningCommand
        {
            get
            {
                return _WarningCommand ??
                        (_WarningCommand = new RelayCommand<Button>(ShowPopup));
            }
        }

        private ICommand _CancelCommand;
        public ICommand CancelCommand
        {
            get { return _CancelCommand ?? (_CancelCommand = new RelayCommand<Button>(HidePopup)); }
        }

        private ICommand _FilterButtonVisibilityCommand;
        public ICommand FilterButtonVisibilityCommand
        {
            get
            {
                return _FilterButtonVisibilityCommand ??
                        (_FilterButtonVisibilityCommand = new RelayCommand<RadioButton>(DoFilterButtonVisibility));
            }
        }

        private ICommand _UnitFilterCommand;
        public ICommand UnitFilterCommand
        {
            get
            {
                return _UnitFilterCommand ??
                        (_UnitFilterCommand = new RelayCommand<Button>(FilterByUnitName));
            }
        }

        private ICommand _OpenPlansCommand;
        public ICommand OpenPlansCommand
        {
            get
            {
                return _OpenPlansCommand ??
                        (_OpenPlansCommand = new RelayCommand<object>(OpenPlansFromDB));
            }
        }

        private ICommand _SavePlansCommand;
        public ICommand SavePlansCommand
        {
            get
            {
                return _SavePlansCommand ??
                        (_SavePlansCommand = new RelayCommand<object>(SavePlansFromDB));
            }
        }

        private ICommand _AddNewActivityEvent;
        public ICommand AddNewActivityEvent
        {
            get
            {
                return _AddNewActivityEvent ??
                        (_AddNewActivityEvent = new RelayCommand<Button>(AddNewScenarioActivity));
            }
        }

        private ICommand _UnitTypeSelectionCommand;
        public ICommand UnitTypeSelectionCommand
        {
            get
            {
                return _UnitTypeSelectionCommand ??
                        (_UnitTypeSelectionCommand = new RelayCommand<ComboBox>(UnitTypeSelectionChanged));
            }
        }

        private ICommand _SettingsUnitTypeSelectionCommand;
        public ICommand SettingsUnitTypeSelectionCommand
        {
            get
            {
                return _SettingsUnitTypeSelectionCommand ??
                        (_SettingsUnitTypeSelectionCommand = new RelayCommand<ComboBox>(SettingsUnitTypeSelectionChanged));
            }
        }

        private ICommand _UnitNameSelectionCommand;
        public ICommand UnitNameSelectionCommand
        {
            get
            {
                return _UnitNameSelectionCommand ??
                        (_UnitNameSelectionCommand = new RelayCommand<ComboBox>(UnitNameSelectionChanged));
            }
        }

        private ICommand _AddActivityCommand;
        public ICommand AddActivityCommand
        {
            get
            {
                return _AddActivityCommand ??
                        (_AddActivityCommand = new RelayCommand<Button>(AddNewActivity));
            }
        }
        private ICommand _DropdownSelectCommand;
        public ICommand DropdownSelectCommand
        {
            get
            {
                return _DropdownSelectCommand ??
                        (_DropdownSelectCommand = new RelayCommand<Button>(SelectMonthYearFromECPopup));
            }
        }

        private ICommand _TextBoxLoadCommand;
        public ICommand TextBoxLoadCommand
        {
            get
            {
                return _TextBoxLoadCommand ??
                        (_TextBoxLoadCommand = new RelayCommand<TextBox>(LoadTextBox));
            }
        }
        private ICommand _UnitNameKeyDownCommand;
        public ICommand UnitNameKeyDownCommand
        {
            get
            {
                return _UnitNameKeyDownCommand ??
                        (_UnitNameKeyDownCommand = new RelayCommand<object>(UnitTextBoxKeyDown));
            }
        }

        private ICommand _SelectedStartDateChangedCommand;
        public ICommand SelectedStartDateChangedCommand
        {
            get
            {
                return _SelectedStartDateChangedCommand ??
                        (_SelectedStartDateChangedCommand = new RelayCommand<DatePicker>(StartDate_SelectedDateChanged));
            }
        }

        private ICommand _StartDateLoadedCommand;
        public ICommand StartDateLoadedCommand
        {
            get
            {
                return _StartDateLoadedCommand ??
                        (_StartDateLoadedCommand = new RelayCommand<DatePicker>(LoadStartDate));
            }
        }
        private ICommand _EndDateLoadedCommand;
        public ICommand EndDateLoadedCommand
        {
            get
            {
                return _EndDateLoadedCommand ??
                        (_EndDateLoadedCommand = new RelayCommand<DatePicker>(LoadEndDate));
            }
        }

        private ICommand _DivisionSelectionCommand;
        public ICommand DivisionSelectionCommand
        {
            get
            {
                return _DivisionSelectionCommand ??
                        (_DivisionSelectionCommand = new RelayCommand<ComboBox>(LoadActivityByDivision));
            }
        }

        private ICommand _ActivityCodeSelectionCommand;
        public ICommand ActivityCodeSelectionCommand
        {
            get
            {
                return _ActivityCodeSelectionCommand ??
                        (_ActivityCodeSelectionCommand = new RelayCommand<ComboBox>(LoadUnitTypeByActivityCode));
            }
        }

        private ICommand _SettingsCommand;
        public ICommand SettingsCommand
        {
            get
            {
                return _SettingsCommand ??
                        (_SettingsCommand = new RelayCommand<HyperlinkButton>(ShowAdminSettings));
            }
        }

        private ICommand _SettingsSubmitCommand;
        public ICommand SettingsSubmitCommand
        {
            get
            {
                return _SettingsSubmitCommand ??
                        (_SettingsSubmitCommand = new RelayCommand<Button>(SubmitAdminSettings));
            }
        }

        private ICommand _SettingsCancelCommand;
        public ICommand SettingsCancelCommand
        {
            get
            {
                return _SettingsCancelCommand ??
                        (_SettingsCancelCommand = new RelayCommand<Button>(CancelAdminSettings));
            }
        }

        private ICommand _CapacityTextBoxLoadCommand;
        public ICommand CapacityTextBoxLoadCommand
        {
            get
            {
                return _CapacityTextBoxLoadCommand ??
                        (_CapacityTextBoxLoadCommand = new RelayCommand<TextBox>(LoadCapacityTextBox));
            }
        }

        private ICommand _IPRTextBoxLoadCommand;
        public ICommand IPRTextBoxLoadCommand
        {
            get
            {
                return _IPRTextBoxLoadCommand ??
                        (_IPRTextBoxLoadCommand = new RelayCommand<TextBox>(LoadIPRTextBox));
            }
        }

        private ICommand _MaxProdTextBoxLoadCommand;
        public ICommand MaxProdTextBoxLoadCommand
        {
            get
            {
                return _MaxProdTextBoxLoadCommand ??
                        (_MaxProdTextBoxLoadCommand = new RelayCommand<TextBox>(LoadMaxProdTextBox));
            }
        }


        private ICommand _LossPercentageTextBoxLoadCommand;
        public ICommand LossPercentageTextBoxLoadCommand
        {
            get
            {
                return _LossPercentageTextBoxLoadCommand ??
                        (_LossPercentageTextBoxLoadCommand = new RelayCommand<TextBox>(LoadUnplannedTextBox));
            }
        }

        private ICommand _MonitoringTextBoxLoadCommand;
        public ICommand MonitoringTextBoxLoadCommand
        {
            get
            {
                return _MonitoringTextBoxLoadCommand ??
                        (_MonitoringTextBoxLoadCommand = new RelayCommand<TextBox>(LoadMonitoringTextBox));
            }
        }

        private ICommand _UnitLayerSelectionCommand;
        public ICommand UnitLayerSelectionCommand
        {
            get
            {
                return _UnitLayerSelectionCommand ??
                        (_UnitLayerSelectionCommand = new RelayCommand<ComboBox>(UnitLayerSelectionChanged));
            }
        }

        private ICommand _UnitMaxProdLayerSelectionCommand;
        public ICommand UnitMaxProdLayerSelectionCommand
        {
            get
            {
                return _UnitMaxProdLayerSelectionCommand ??
                        (_UnitMaxProdLayerSelectionCommand = new RelayCommand<ComboBox>(UnitLayerMaxProdSelectionChanged));
            }
        }


        private ICommand _OCCPRadialSwitchCheckedCommand;
        public ICommand OCCPRadialSwitchCheckedCommand
        {
            get
            {
                return _OCCPRadialSwitchCheckedCommand ??
                        (_OCCPRadialSwitchCheckedCommand = new RelayCommand<RadioButton>(OCCPRadialSwitchChecked));
            }
        }

        private ICommand _ScenarioNameTextBoxLoadCommand;
        public ICommand ScenarioNameTextBoxLoadCommand
        {
            get
            {
                return _ScenarioNameTextBoxLoadCommand ??
                        (_ScenarioNameTextBoxLoadCommand = new RelayCommand<TextBox>(LoadScenarioNameTextBox));
            }
        }

        private ICommand _ScenarioNameEnterCommand;
        public ICommand ScenarioNameEnterCommand
        {
            get
            {
                return _ScenarioNameEnterCommand ??
                        (_ScenarioNameEnterCommand = new RelayCommand<object>(UpdateScenarioNameByKeyPress));
            }
        }



        #endregion

        #region Constructor
        public ImportVM()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                _validationResults = new List<ValidationResult>();

                strECSender = Guid.NewGuid().ToString();
                strECReceiver = Guid.NewGuid().ToString();
                strMCSender = Guid.NewGuid().ToString();
                strMCReceiver = Guid.NewGuid().ToString();

                localMessageECSender = new LocalMessageSender(strECSender, LocalMessageSender.Global);
                localMessageECSender.SendCompleted += new EventHandler<SendCompletedEventArgs>(localMessageECSender_SendCompleted);

                localMessageECReceiver = new LocalMessageReceiver(strECReceiver,
                                                              ReceiverNameScope.Global,
                                                              LocalMessageReceiver.AnyDomain);

                localMessageMCSender = new LocalMessageSender(strMCSender, LocalMessageSender.Global);

                localMessageMCSender.SendCompleted += new EventHandler<SendCompletedEventArgs>(localMessageMCSender_SendCompleted);

                localMessageMCReceiver = new LocalMessageReceiver(strMCReceiver,
                                                              ReceiverNameScope.Global,
                                                              LocalMessageReceiver.AnyDomain);


                localMessageECReceiver.MessageReceived += new EventHandler<MessageReceivedEventArgs>(localMessageECReceiver_MessageReceived);
                localMessageECReceiver.Listen();

                localMessageMCReceiver.MessageReceived += new EventHandler<MessageReceivedEventArgs>(localMessageMCReceiver_MessageReceived);
                localMessageMCReceiver.Listen();

                ServiceLocator.Get<MainPageVM>().OnImportClick += new EventHandler(ImportVM_OnImportClick);

                GetInitialDataFromDB();

                //This is for saveas effective capacity popup
                InitializeECPopup();
            }
        }

        private void InitializeECPopup()
        {
            for (int i = 0; i <= 10; i++)
                YearList.Add(DateTime.Now.Year + i);
            SelectedMonth = MonthList[0];
            SelectedYear = YearList[0];
        }

        private void GetInitialDataFromDB()
        {
            //GetUserRolesFromDB();
            GetUserRolesInformation();
            GetScenariosFromDB();
            GetDivisionActivityCode();
            GetUnitsFromDB();
            GetUnitCapacity();
            GetUnitLayer();
            GetSettingsData();
        }



        void localMessageECReceiver_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            IsECBrowserOpened = false;
        }

        void localMessageMCReceiver_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            IsMCBrowserOpened = false;
        }


        private int attempt = 1;
        private const int MAX_ATTEMPTS = 10000;
        void localMessageECSender_SendCompleted(object sender, SendCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                attempt++;
                if (attempt > MAX_ATTEMPTS)
                {
                    MessageBox.Show("Some error occured. Click calculate button again");
                    return;
                }

                localMessageECSender.SendAsync(retXml);
            }
            attempt = 1;
        }

        void localMessageMCSender_SendCompleted(object sender, SendCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                attempt++;
                if (attempt > MAX_ATTEMPTS)
                {
                    MessageBox.Show("Some error occured. Click calculate button again");
                    return;
                }

                localMessageMCSender.SendAsync(retXml);
            }
            attempt = 1;
        }

        private void GetUserRolesInformation()
        {
            FifpLoginUserRole = new FIFPGroupUser();
            FifpLoginUserRole.UserGroupId = App.UserGroupId;
            FifpLoginUserRole.LoginUserId = App.LoginUserId;
            FifpLoginUserRole.UserName = App.LoginUserName;
            FifpLoginUserRole.Email = App.LoginEmail;
            FifpLoginUserRole.Phone = App.LoginPhone;

            if (FifpLoginUserRole != null && FifpLoginUserRole.UserGroupId == FIFPConstants.USER_ROLES_ADMIN_ID)
                CalculateMaxVisibility = Visibility.Visible;
            else
                CalculateMaxVisibility = Visibility.Collapsed;
        }

        private void GetUserRolesFromDB()
        {
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            ServiceLocator.Get<MainPageVM>().IsLoading = true;
            ServiceLocator.Get<MainPageVM>().LoadingMessage = FIFPConstants.INTIAL_LOADING_MESSAGE;
            string[] param = new string[] { App.LoginUserName };
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.GET_GROUPUSERS, param, "UserRoles");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForUserRolesDataCompleted);
        }

        private void ImportVM_QueryForUserRolesDataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            if (e != null && e.Result != null && e.Error == null && Convert.ToString(e.UserState) == "UserRoles")
            {
                StringReader reader = new StringReader(e.Result.Any1.ToString());
                XmlReader xmlR = XmlReader.Create(reader);

                XDocument doc = XDocument.Load(xmlR);
                //if (doc != null)
                //{
                //    LoginUserRole = (from item in doc.Descendants("Query")
                //                     select new UserGroup { UserRole = item.Element("Role") != null ? Convert.ToString(item.Element("Role").Value) : string.Empty }).FirstOrDefault();
                //    if (LoginUserRole != null && LoginUserRole.UserRole == FIFPConstants.USER_ROLES_ADMIN)
                //        CalculateMaxVisibility = Visibility.Visible;
                //    else
                //        CalculateMaxVisibility = Visibility.Collapsed;
                //}
                //GetScenariosFromDB();
            }
        }

        private void BuildMenu(List<Scenario> scenarioList)
        {
            OpenMenuItems = new ObservableCollection<MenuItem>();
            SaveMenuItems = new ObservableCollection<MenuItem>();
            MenuItem planMenuItem = new MenuItem() { ScenarioName = "Plan" };
            List<Scenario> openPlans = scenarioList.Where(s => s.PlanType == "" || s.PlanType == "EC").ToList<Scenario>();
            Scenario ecScenario = scenarioList.Where(s => s.PlanType == "EC" && s.ScenarioName == "EC Plan " + DateTime.Now.Year).FirstOrDefault();
            if (ecScenario != null)
                BECScanrio = true;
            ObservableCollection<MenuItem> pSubmenu = new ObservableCollection<MenuItem>() { };
            foreach (Scenario scenario in openPlans) //Load menu for admin
            {
                if (scenario.ScenarioName == FIFPConstants.ORIGINAL_PLAN && FifpLoginUserRole.UserGroupId == FIFPConstants.USER_ROLE_USER_ID)
                { }
                else
                    pSubmenu.Add(new MenuItem() { ScenarioId = scenario.ScenarioId, ScenarioName = scenario.ScenarioName });

            }

            planMenuItem.SubItems = pSubmenu;

            MenuItem scenarioItem = new MenuItem() { ScenarioName = "Scenario" };
            ObservableCollection<MenuItem> sSubmenu = new ObservableCollection<MenuItem>() { };
            MenuItem myScenarioItem = new MenuItem() { ScenarioName = "My Scenario" };
            myScenarioItem.MenuItemVisibility = Visibility.Collapsed;
            sSubmenu.Add(myScenarioItem);

            CurrentUserScenarioList = scenarioList.Where(s => s.PlanType == "USC" || s.PlanType == "EC").ToList<Scenario>();
            //ServiceLocator.Get<ChartViewModel>().BuildScenarioCombo();

            List<Scenario> loggedInUserScenarioList = scenarioList.Where(s => s.PlanType == "USC" && s.UserName == App.LoginUserName).ToList<Scenario>();
            ObservableCollection<MenuItem> scenarioSubmenu = new ObservableCollection<MenuItem>() { };
            foreach (Scenario scenario in loggedInUserScenarioList)///Load menu for user scenario
            {
                scenarioSubmenu.Add(new MenuItem() { ScenarioId = scenario.ScenarioId, ScenarioName = scenario.ScenarioName });
            }
            myScenarioItem.SubItems = scenarioSubmenu;

            if (FifpLoginUserRole.UserGroupId == FIFPConstants.USER_ROLES_ADMIN_ID || FifpLoginUserRole.UserGroupId == FIFPConstants.USER_ROLE_INTEGRATOR_ID)
            {
                //Others Scenario
                MenuItem scenarioOthersItem = new MenuItem() { ScenarioName = "Others" };
                List<Scenario> allScenarioUsersList = scenarioList.Where(s => s.PlanType == "USC" && s.UserName != App.LoginUserName).ToList<Scenario>();
                List<string> userList = allScenarioUsersList.Select(s => s.UserName).Distinct().ToList<string>();
                ObservableCollection<MenuItem> usersMenuitem = new ObservableCollection<MenuItem>();
                if (userList != null && userList.Count > 0)
                {
                    foreach (string user in userList)
                    {
                        MenuItem userItem = new MenuItem() { ScenarioName = user };
                        List<Scenario> scenarioUsersList = allScenarioUsersList.Where(s => s.UserName.Equals(user)).ToList<Scenario>();
                        if (scenarioUsersList != null && scenarioUsersList.Count > 0)
                        {
                            usersMenuitem.Add(userItem);
                            ObservableCollection<MenuItem> scenarioUsersSubmenu = new ObservableCollection<MenuItem>();
                            foreach (Scenario scenarioUserItem in scenarioUsersList)
                                scenarioUsersSubmenu.Add(new MenuItem() { ScenarioId = scenarioUserItem.ScenarioId, ScenarioName = scenarioUserItem.ScenarioName });
                            userItem.SubItems = scenarioUsersSubmenu;
                        }
                    }
                    scenarioOthersItem.SubItems = usersMenuitem;
                }
                sSubmenu.Add(scenarioOthersItem);
            }

            scenarioItem.SubItems = sSubmenu;
            OpenMenuItems.Add(planMenuItem);
            OpenMenuItems.Add(scenarioItem);

            //
            MenuItem saveMenuItem = new MenuItem() { ScenarioName = "Save" };
            SaveMenuItems.Add(saveMenuItem);
            MenuItem saveAsItem = new MenuItem() { ScenarioName = "SaveAs" };
            ObservableCollection<MenuItem> saveAsSubmenu = new ObservableCollection<MenuItem>() { };
            MenuItem saveAsplanItem = new MenuItem() { ScenarioName = "Plan" };
            if (FifpLoginUserRole.UserGroupId == FIFPConstants.USER_ROLES_ADMIN_ID || FifpLoginUserRole.UserGroupId == FIFPConstants.USER_ROLE_INTEGRATOR_ID)
                saveAsSubmenu.Add(saveAsplanItem);
            saveAsSubmenu.Add(new MenuItem() { ScenarioName = "Scenario" });
            saveAsItem.SubItems = saveAsSubmenu;

            ObservableCollection<MenuItem> saveAsPlanSubmenu = new ObservableCollection<MenuItem>() { };
            if (FifpLoginUserRole.UserGroupId == FIFPConstants.USER_ROLE_INTEGRATOR_ID)
                saveAsPlanSubmenu.Add(new MenuItem() { ScenarioName = "Integrated Plan" });
            if (FifpLoginUserRole.UserGroupId == FIFPConstants.USER_ROLES_ADMIN_ID)
            {
                saveAsPlanSubmenu.Add(new MenuItem() { ScenarioName = "EC Plan" });
                saveAsPlanSubmenu.Add(new MenuItem() { ScenarioName = "EC Updated Plan" });
                saveAsPlanSubmenu.Add(new MenuItem() { ScenarioName = "New Name" });
            }
            saveAsplanItem.SubItems = saveAsPlanSubmenu;
            SaveMenuItems.Add(saveAsItem);
        }

        private void GetScenariosFromDB()
        {
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_ALL_SCENARIOS_QUERY_ID, null, "DBScenario");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForScenarioDataCompleted);
        }

        private void ImportVM_QueryForScenarioDataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {

            if (e.Result != null && e.Error == null)
            {
                if (e.UserState.ToString() == "DBScenario")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            List<Scenario> scenarioList = (from item in doc.Descendants("Query")
                                                           select new Scenario
                                                           {
                                                               ScenarioId = item.Element("scenarioId") != null ? Convert.ToInt32(item.Element("scenarioId").Value) : 0,
                                                               ScenarioName = item.Element("scenarioName") != null ? Convert.ToString(item.Element("scenarioName").Value) : string.Empty,
                                                               ScenarioDescription = item.Element("scenarioName") != null ? Convert.ToString(item.Element("scenarioName").Value) : string.Empty,
                                                               UserName = item.Element("userName") != null ? Convert.ToString(item.Element("userName").Value) : string.Empty,
                                                               PlanType = item.Element("planType") != null ? Convert.ToString(item.Element("planType").Value) : string.Empty
                                                           }).ToList<Scenario>();
                            ScenarioList = scenarioList;
                            BuildMenu(scenarioList);
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                MessageBox.Show("Database connection error while getting scenario information.");
            }
        }

        private void OpenPlansFromDB(object e)
        {
            if (IsAnimationStarted)
            {
                IsAnimationStarted = false;
                StoryboardManager.PlayStoryboard(FIFPConstants.SETTINGSFLIP_STOP, s => { }, null);
            }
            RadRoutedEventArgs eventArgs = e as RadRoutedEventArgs;
            if (eventArgs != null)
            {
                RadMenuItem radItem = eventArgs.OriginalSource as RadMenuItem;
                if (radItem != null)
                {
                    MenuItem item = radItem.DataContext as MenuItem;
                    if (item != null)
                    {
                        CurrentScenario = new Scenario() { ScenarioId = item.ScenarioId, ScenarioName = item.ScenarioName };
                        if (item.ScenarioName != "Plan" && item.ScenarioName != "Scenario" && item.ScenarioName != "My Scenario" && item.ScenarioName != "Others")
                        {
                            CurrentScenarioId = item.ScenarioId;
                            CurrentScenarioName = item.ScenarioName;
                            ServiceLocator.Get<MainPageVM>().ScenarioName = "Current Scenario: " + item.ScenarioName;

                            //ServiceLocator.Get<ChartViewModel>().ResetScenarioFilterData();
                            BReloadScenario = false;

                            //Reset all pages
                            if (ServiceLocator.Get<MainPageVM>().IsImportChecked)
                                ServiceLocator.Get<FilterVM>().ResetFilterData();
                            else
                                ServiceLocator.Get<FilterVM>().ResetLsdFilterData();
                            ServiceLocator.Get<OverlapVM_New>().Reset();
                            ServiceLocator.Get<ShutdownMngVM>().Reset();
                            ServiceLocator.Get<OptMngVM>().Reset();

                            if (DeletedActivityIds.Count > 0)
                                DeletedActivityIds.Clear();
                            if (item.ScenarioName != FIFPConstants.ORIGINAL_PLAN)
                                ServiceLocator.Get<MainPageVM>().IsIntegrationEnabled = true;
                            else
                                ServiceLocator.Get<MainPageVM>().IsIntegrationEnabled = false;
                            LoadScenarioFromDB(item.ScenarioName);
                        }
                    }
                }
            }
        }

        private void SavePlansFromDB(object e)
        {
            SelectedECPlan = string.Empty;
            if (IsAnimationStarted)
            {
                IsAnimationStarted = false;
                StoryboardManager.PlayStoryboard(FIFPConstants.SETTINGSFLIP_STOP, s => { }, null);
            }
            RadRoutedEventArgs eventArgs = e as RadRoutedEventArgs;
            if (eventArgs != null)
            {
                RadMenuItem radItem = eventArgs.OriginalSource as RadMenuItem;
                if (radItem != null)
                {
                    MenuItem item = radItem.DataContext as MenuItem;
                    if (item != null && !string.IsNullOrEmpty(item.ScenarioName) && CurrentScenarioId > 0) //normal User scenario textbox will enable after open any scenario
                    {
                        switch (item.ScenarioName)
                        {
                            case FIFPConstants.INTEGRATD_PLAN:
                                SaveAsScenario(FIFPConstants.INTEGRATD_PLAN, "", "SaveAsBaseScenario");
                                break;
                            case FIFPConstants.SAVE_PLAN:
                                if (CurrentScenarioName == FIFPConstants.ORIGINAL_PLAN)
                                {
                                    ShowPopup(FIFPConstants.WARNINGTITLE_ORIGINALPLAN_SAVE, FIFPConstants.WARNINGMESSAGE_ORIGINALPLAN_SAVE);
                                }
                                else
                                    SaveScenario();
                                break;
                            case FIFPConstants.EC_PLAN:
                                SelectedECPlan = FIFPConstants.EC_PLAN;
                                MonthComboVisibility = Visibility.Collapsed;
                                ecPopup = new ECPopup();
                                ecPopup.Closed += new EventHandler(ecPopup_Closed);
                                ecPopup.Show();
                                break;
                            case FIFPConstants.EC_UPDATED_PLAN:
                                SelectedECPlan = FIFPConstants.EC_UPDATED_PLAN;
                                MonthComboVisibility = Visibility.Visible;
                                ecPopup = new ECPopup();
                                ecPopup.Closed += new EventHandler(ecPopup_Closed);
                                ecPopup.Show();
                                break;
                            case FIFPConstants.DISPLAY_SCENARIO:
                                ScenarioName = CurrentScenarioName;
                                scenarioPopup = new CreateScenarioPopup();
                                scenarioPopup.Closed += new EventHandler(scenarioPopup_Closed);
                                scenarioPopup.Show();
                                break;
                            case FIFPConstants.EC_NEWSCENARIO:
                                SelectedECPlan = FIFPConstants.EC_NEWSCENARIO;
                                ScenarioName = CurrentScenarioName;
                                scenarioPopup = new CreateScenarioPopup();
                                scenarioPopup.Closed += new EventHandler(scenarioPopup_Closed);
                                scenarioPopup.Show();
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }

        private void LoadScenarioFromDB(string scenarioName)
        {

            ServiceLocator.Get<MainPageVM>().IsLoading = true;
            ServiceLocator.Get<MainPageVM>().LoadingMessage = string.Format(FIFPConstants.LOADING_SCENARIO, scenarioName);
            DateTime startDate = new DateTime(DateTime.Now.Year, 1, 1);
            DateTime endDate = new DateTime(DateTime.Now.Year + 4, 12, 31);
            string[] param = new string[] { scenarioName };
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_PLAN_BY_NAME_QUERY_ID, param, "OpenScenario");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForDataCompleted);
        }

        private void GetSwitchedRadialFromDB()
        {
            string[] param = new string[] { Convert.ToString(CurrentScenarioId) };
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_Select_SWITCHEDRADIAL_QUERY_ID, param, "SelectSwitchedRadial");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForSelectSwitchedRadialCompleted);
        }

        void ImportVM_QueryForSelectSwitchedRadialCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            if (e.Result != null && e.Error == null)
            {
                if (Convert.ToString(e.UserState) == "SelectSwitchedRadial")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);
                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            radialSwitchListFromDB = (from item in doc.Descendants("Query")
                                                      select new RadialSwitch
                                                   {
                                                       ScenarioId = item.Element("Scenario_ID") != null ? Convert.ToInt32(item.Element("Scenario_ID").Value) : -1,
                                                       UnitId = item.Element("Unit_ID") != null ? Convert.ToInt32(item.Element("Unit_ID").Value) : -1,
                                                       ParentUnitId = item.Element("OCCP_Unit_ID") != null ? Convert.ToInt32(item.Element("OCCP_Unit_ID").Value) : -1,
                                                       StartDate = Convert.ToDateTime(item.Element("StartDate").Value),
                                                       EndDate = Convert.ToDateTime(item.Element("EndDate").Value)
                                                   }).ToList<RadialSwitch>();
                        }
                        BindData();//
                        ServiceLocator.Get<MainPageVM>().IsLoading = false;
                    }
                    catch (Exception ex)
                    {
                        ServiceLocator.Get<MainPageVM>().IsLoading = false;
                    }
                }
            }
        }


        private void GetReducedCapacityFromDB()
        {
            string[] param = new string[] { Convert.ToString(CurrentScenarioId) };
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_Select_ReducedCapacity_QUERY_ID, param, "SelectReducedCapacity");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForSelectReducedCapacityCompleted);
        }

        void ImportVM_QueryForSelectReducedCapacityCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            if (e.Result != null && e.Error == null)
            {
                if (Convert.ToString(e.UserState) == "SelectReducedCapacity")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);
                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            ReducedCapacityList = (from item in doc.Descendants("Query")
                                                   select new ReducedCapacity
                                                   {
                                                       PlanId = item.Element("Plan_ID") != null ? Convert.ToInt32(item.Element("Plan_ID").Value) : -1,
                                                       ScenarioId = item.Element("Scenario_ID") != null ? Convert.ToInt32(item.Element("Scenario_ID").Value) : -1,
                                                       ParentUnitId = item.Element("Parent_Unit_ID") != null ? Convert.ToInt32(item.Element("Parent_Unit_ID").Value) : -1,
                                                       UnitId = item.Element("Unit_ID") != null ? Convert.ToInt32(item.Element("Unit_ID").Value) : -1,
                                                       StartDate = Convert.ToDateTime(item.Element("Start_Date").Value),
                                                       EndDate = Convert.ToDateTime(item.Element("End_Date").Value),
                                                       OriginalUnitCapacity = item.Element("Original_Capacity") != null ? Convert.ToDouble(item.Element("Original_Capacity").Value) : 0,
                                                       ReducedUnitCapacity = item.Element("Reduced_Capacity") != null ? Convert.ToDouble(item.Element("Reduced_Capacity").Value) : 0
                                                   }).ToList<ReducedCapacity>();
                        }
                        //ServiceLocator.Get<MainPageVM>().IsLoading = false;
                    }
                    catch (Exception ex)
                    {
                        ServiceLocator.Get<MainPageVM>().IsLoading = false;
                    }
                }
            }
        }

        void ecPopup_Closed(object sender, EventArgs e)
        {
        }

        private void SelectMonthYearFromECPopup(Button btnOk)
        {
            ecPopup.Close();
            if (SelectedECPlan == FIFPConstants.EC_PLAN)
                SaveAsScenario(SelectedECPlan + " " + SelectedYear, "EC", "SaveAsBaseScenario");
            else if (SelectedECPlan == FIFPConstants.EC_UPDATED_PLAN)
                SaveAsScenario(SelectedECPlan + " - " + SelectedMonth + " " + SelectedYear, "EC", "SaveAsBaseScenario");
        }

        private void AddNewActivity(Button btnAdd)
        {
            BValidate = true;
            if (CheckNewActivityValidation() && IsAddButtonEnabled)
            {
                BValidate = false;
                string strActivities = string.Empty;
                FIFPAppointment appointment = new FIFPAppointment();
                appointment.ActivityCode = SelectedActivityCode.Name;
                appointment.ActivityId = SelectedActivityCode.Id;
                appointment.ActivityCodeDescription = SelectedActivityCode.ActivityDescription;
                appointment.UnitStatus = SelectedActivityCode.ActivityStatus;
                appointment.Subject = SelectedActivityCode.Name;
                appointment.Start = appointment.OriginalStart = Convert.ToDateTime(ActivityStartDate); // Need to change it
                appointment.End = appointment.OriginalEnd = new DateTime(ActivityEndDate.Year, ActivityEndDate.Month, ActivityEndDate.Day, 23, 59, 59);
                appointment.Division = SelectedDivisionName.Name;
                appointment.DivisionId = SelectedActivityCode.DivisionId;
                appointment.UnitType = SelectedUnitType;
                appointment.UnitID = SelectedActivityUnit.UnitID;
                appointment.FluidType = SelectedActivityUnit.FluidType;
                appointment.UnitName = SelectedActivityUnit.UnitName;
                appointment.Remarks = CommentsText;
                appointment.IsModified = 1;
                appointment.PlanActivityId = ++newactivityId;

                strActivities = appointment.IsModified.ToString() + "|" + appointment.UnitID + "|" + appointment.ActivityId + "|" + appointment.DivisionId + "|" + appointment.Start.ToString("dd/MM/yyyy") + "|" + appointment.End.ToString("dd/MM/yyyy") + "|" + appointment.Remarks + "|" + appointment.PlanActivityId + "|" + appointment.LSDDeletedIds + "|" + appointment.SelectedOilString + "|" + appointment.CapacityPercentage + "|" + appointment.ReducedCapacity + "|" + appointment.IsAppliedSimops + "|" + appointment.IsAppliedLSDSimops + "|" + appointment.IsAppliedCrossingLine + "|" + appointment.IsBypassMOL + "|" + appointment.DB_OverlapId + "|" + appointment.IsRDVisibility + "|";
                string[] param = null;
                if (!string.IsNullOrEmpty(strActivities))
                    param = new string[] { strActivities, Convert.ToString(CurrentScenarioId) };
                else
                    param = new string[] { null, Convert.ToString(CurrentScenarioId) };
                ServiceLocator.Get<MainPageVM>().IsLoading = true;
                ServiceLocator.Get<MainPageVM>().LoadingMessage = FIFPConstants.LOADING_ADDNEWACTIVITY_MESSAGE;

                RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
                queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.ADDNEWACTIVITY_QUERY_ID, param, "AddnewActivity");
                queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForAddNewActivityCompleted);


            }
            else
            {
                BValidate = false;
                IsAddButtonEnabled = true;
            }
        }

        void ImportVM_QueryForAddNewActivityCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            ServiceLocator.Get<MainPageVM>().IsLoading = false;
            if (e.Result != null && e.Error == null)
            {
                if (Convert.ToString(e.UserState) == "AddnewActivity")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);
                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            List<Scenario> retScenarioList = (from item in doc.Descendants("Query")
                                                              select new Scenario
                                                              {
                                                                  ScenarioId = item.Element("scenarioId") != null ? Convert.ToInt32(item.Element("scenarioId").Value) : 0,
                                                                  ScenarioName = item.Element("scenarioName") != null ? Convert.ToString(item.Element("scenarioName").Value) : string.Empty,
                                                                  ScenarioDescription = item.Element("scenarioName") != null ? Convert.ToString(item.Element("scenarioName").Value) : string.Empty,
                                                                  NewPlanId = item.Element("realNewPlanId") != null ? Convert.ToInt32(item.Element("realNewPlanId").Value) : 0,
                                                                  ActivityId = item.Element("tempNewPlanId") != null ? Convert.ToInt32(item.Element("tempNewPlanId").Value) : 0,
                                                              }).ToList<Scenario>();
                            if (retScenarioList != null && retScenarioList.Count > 0)
                            {
                                Scenario newActivity = retScenarioList[0];
                                if (newActivity != null)
                                    ReloadScheduleViewAfterAddActivity(newActivity.NewPlanId);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ServiceLocator.Get<MainPageVM>().IsLoading = false;
                    }
                }
            }
        }

        private void ReloadScheduleViewAfterAddActivity(int newPlanId)
        {
            FIFPAppointment appointment = new FIFPAppointment();
            appointment.ActivityCode = SelectedActivityCode.Name;
            appointment.ActivityId = SelectedActivityCode.Id;
            appointment.ActivityCodeDescription = SelectedActivityCode.ActivityDescription;
            appointment.UnitStatus = SelectedActivityCode.ActivityStatus;
            appointment.Subject = SelectedActivityCode.Name;
            appointment.Start = appointment.OriginalStart = Convert.ToDateTime(ActivityStartDate); // Need to change it
            appointment.End = appointment.OriginalEnd = new DateTime(ActivityEndDate.Year, ActivityEndDate.Month, ActivityEndDate.Day, 23, 59, 59);
            appointment.Division = SelectedDivisionName.Name;
            appointment.DivisionId = SelectedActivityCode.DivisionId;
            appointment.UnitType = SelectedUnitType;
            appointment.UnitID = SelectedActivityUnit.UnitID;
            appointment.FluidType = SelectedActivityUnit.FluidType;
            appointment.UnitName = SelectedActivityUnit.UnitName;
            appointment.Remarks = CommentsText;
            appointment.PlanActivityId = newPlanId;//It's just for assign the newly added activities planId to the corresponding objects.
            appointment.PlanID = newPlanId; //We need planId for each appointment for subsequent page process.It's not going to be stored into database.

            appointment.nIndex = (appointment.UnitName == FIFPConstants.UNITTYPE_MOL && appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 1 : (appointment.UnitType == FIFPConstants.UNITTYPE_USSC_PLATFORM) ? 2 : (appointment.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL && appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 3 : (appointment.UnitType == FIFPConstants.UNITTYPE_PLATFORM) ? 4 : (appointment.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR) ? 5 : (appointment.UnitType == FIFPConstants.UNITTYPE_SEPERATOR) ? 6 : (appointment.UnitType == FIFPConstants.UNITTYPE_MODULE) ? 7 : (appointment.UnitType == FIFPConstants.UNITTYPE_SPHEROID) ? 8 : (appointment.UnitType == FIFPConstants.UNITTYPE_STRIPPER) ? 9 : (appointment.UnitType == FIFPConstants.UNITTYPE_RADIAL) ? 10 : (appointment.UnitType == FIFPConstants.UNITTYPE_TOWER) ? 11 : (appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 12 : (appointment.UnitType == FIFPConstants.UNITTYPE_WELL) ? 13 : (appointment.UnitType == FIFPConstants.UNITTYPE_STRING ? 14 : 0);

            ScenarioPlans.Add(appointment);
            if (appointment.Start >= ServiceLocator.Get<FilterVM>().StartDate && appointment.End <= ServiceLocator.Get<FilterVM>().EndDate)
                ImportPlans.Add(appointment);


            GenerateLinkedShutdownPlansForNewActivity(appointment); //Need to check linked shutdown Generations later

            //Commented the below line for carry over the selected start date and end date throught subsequent pages.
            //ServiceLocator.Get<FilterVM>().EndDate = appointment.End > ServiceLocator.Get<FilterVM>().EndDate ? appointment.End : ServiceLocator.Get<FilterVM>().EndDate;
            activityPopup.Close();
            IsAddActivityButtonEnabled = true;
            IsAddButtonEnabled = false;
            BindData();
            ResetFields();
        }

        #region CheckValidation
        private bool CheckNewActivityValidation()
        {
            bool bInsert = true;
            if (IsUnitTypeEnabled && SelectedUnitType == FIFPConstants.SELECT_UNIT_TYPE)
            {
                bInsert = false;
                NotifyPropertyChanged(() => SelectedUnitType);
            }
            if (IsUnitNameEnabled && SelectedActivityUnit.UnitName == FIFPConstants.SELECT_UNITNAME)
            {
                bInsert = false;
                NotifyPropertyChanged(() => SelectedActivityUnit);
            }
            if (SelectedDivisionName.Name == FIFPConstants.SELECT_DIVISION)
            {
                bInsert = false;
                NotifyPropertyChanged(() => SelectedDivisionName);
            }
            if (IsActivityCodeEnabled && SelectedActivityCode.Name == FIFPConstants.SELECT_ACTIVITY)
            {
                bInsert = false;
                NotifyPropertyChanged(() => SelectedActivityCode);
            }

            if (ActivityStartDate > ActivityEndDate)
            {
                bInsert = false;
                NotifyPropertyChanged(() => ActivityStartDate);
            }
            if (ActivityEndDate < ActivityStartDate)
            {
                bInsert = false;
                NotifyPropertyChanged(() => ActivityEndDate);
            }

            return bInsert;
        }
        #endregion

        #region GetDivisionActivityCode
        private void GetDivisionActivityCode()
        {
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_ACTIVITYTYPES_AND_DIVISION_QUERY_ID, null, "DivisionActivityCode");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForDivisionDataCompleted);
        }
        #endregion

        private void AddNewScenarioActivity(Button btnAdd)
        {

            if (IsAnimationStarted)
            {
                IsAnimationStarted = false;
                StoryboardManager.PlayStoryboard(FIFPConstants.SETTINGSFLIP_STOP, s => { }, null);
            }
            ResetFields();
            ActivityStartDate = DateTime.Now;
            ActivityEndDate = DateTime.Now.AddDays(1);
            IsAddActivityButtonEnabled = false;
            IsAddButtonEnabled = true;
            //Show activity dialog
            activityPopup = new AddActivityPopup();
            activityPopup.Closed += new EventHandler(activityPopup_Closed);
            activityPopup.Show();
            IsAddActivityButtonEnabled = false;
            IsAddButtonEnabled = true;
        }

        void ImportVM_QueryForDivisionDataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            if (e.Result != null && e.Error == null)
            {
                if (Convert.ToString(e.UserState) == "DivisionActivityCode")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            ActivityCodeDivisionList = (from item in doc.Descendants("Query")
                                                        select new ActivityType
                                                        {
                                                            Id = item.Element("id") != null ? Convert.ToInt32(item.Element("id").Value) : -1,
                                                            Name = item.Element("name") != null ? Convert.ToString(item.Element("name").Value) : string.Empty,
                                                            Type = item.Element("type") != null ? Convert.ToString(item.Element("type").Value) : string.Empty,
                                                            DivisionId = item.Element("divisionId") != null ? Convert.ToInt32(item.Element("divisionId").Value) : -1,
                                                            ActivityStatus = item.Element("Status") != null ? Convert.ToString(item.Element("Status").Value) : string.Empty,
                                                            ActivityDescription = item.Element("Description") != null ? Convert.ToString(item.Element("Description").Value) : string.Empty,
                                                        }).ToList<ActivityType>();

                            if (OnDivisionListDataCompleted != null)
                                OnDivisionListDataCompleted(this, new CustomEventArgs<List<string>>(ActivityCodeDivisionList.Where(s => s.Type == "d").Select(s => s.Name).ToList<string>()));

                            DivisionCodeList.Add(new ActivityType() { Name = FIFPConstants.SELECT_DIVISION });
                            DivisionCodeList.AddRange(ActivityCodeDivisionList.Where(s => s.Type == "d").ToList<ActivityType>());
                            if (DivisionCodeList != null && DivisionCodeList.Count > 0)
                            {
                                SelectedDivisionName = DivisionCodeList[0];

                            }


                            //ActivityCodeList.Add(new ActivityType() { Name = FIFPConstants.SELECT_ACTIVITY });
                            //SelectedActivityCode = ActivityCodeList[0];

                            //ActivityCodeList = ActivityCodeDivisionList.Where(s => s.Type == "a" && s.DivisionId == SelectedDivisionName.Id).ToList<ActivityType>();
                            //if (ActivityCodeList != null && ActivityCodeList.Count > 0)
                            //    SelectedActivityCode = ActivityCodeList[0];


                        }
                    }
                    catch (Exception ex)
                    {
                        IsAddActivityButtonEnabled = true;
                    }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                MessageBox.Show("Database connection error while getting division-activitycode information.");
            }
        }

        private void GetUnitLayer()
        {
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_UNIT_LAYER_QUERY_ID, null, "UnitLayer");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForUnitLayerCompleted);
        }

        void ImportVM_QueryForUnitLayerCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            if (e.Result != null && e.Error == null)
            {
                if (e.UserState.ToString() == "UnitLayer")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            List<UnitLayer> unitLayerList = (from item in doc.Descendants("Query")
                                                             select new UnitLayer
                                     {
                                         unitID = Convert.ToInt32(item.Element("Unit_ID").Value),
                                         LayerID = Convert.ToInt32(item.Element("LayerID").Value),
                                         layerName = item.Element("Layer_Code") != null ? Convert.ToString(item.Element("Layer_Code").Value) : string.Empty,
                                         IPR = item.Element("IPR") != null ? Convert.ToDouble(item.Element("IPR").Value) : -1,
                                         MaxProduction = item.Element("MaxProduction") != null ? Convert.ToDouble(item.Element("MaxProduction").Value) : -1,
                                         percentage = item.Element("Percentage") != null ? Convert.ToDouble(item.Element("Percentage").Value) : 0
                                     }).ToList<UnitLayer>();

                            List<Layer> layerList = new List<Layer>();
                            layerList.Add(new Layer() { LayerName = FIFPConstants.SELECT_LAYER });
                            List<UnitLayer> sortedList = unitLayerList.GroupBy(g => g.layerName).Select(s => s.First()).ToList<UnitLayer>();
                            if (sortedList != null && sortedList.Count > 0)
                            {
                                foreach (UnitLayer layer in sortedList)
                                    layerList.Add(new Layer() { LayerName = layer.layerName, LayerID = layer.LayerID, IPR = layer.IPR, MaxProduction = layer.MaxProduction });
                            }
                            if (layerList != null && layerList.Count > 0)
                                LayerList = layerList;
                            SelectedLayer = LayerList[0];
                            SelectedMaxProdLayer = LayerList[0];

                            foreach (UnitLayer ul in unitLayerList)
                            {
                                AddtoLayerUnitsDictionary(ul);
                            }

                            isLoadingUnitLayerCompleted = true;
                            if (isLoadingUnitCapacityCompleted == true && importPlans.Count != 0)
                                IsCalButtonEnabled = true;
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                MessageBox.Show("Database connection error while fetching unit layer data.");
            }
        }

        private void GetSettingsData()
        {
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_SETTINGS_QUERY_ID, null, "SettingsData");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForSettingsDataCompleted);
        }

        void ImportVM_QueryForSettingsDataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            ServiceLocator.Get<MainPageVM>().IsLoading = false;
            if (e.Result != null && e.Error == null)
            {
                if (e.UserState.ToString() == "SettingsData")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            List<SettingsData> settingsDataList = (from item in doc.Descendants("Query")
                                                                   select new SettingsData
                                        {
                                            FieldID = Convert.ToInt32(item.Element("FieldID").Value),
                                            FieldName = Convert.ToString(item.Element("FieldName").Value),
                                            CurrentUnplannedLossesPercentage = Convert.ToDouble(item.Element("UnPlannedLoss").Value) * 100,
                                            CurrentMonitoringPercentage = Convert.ToDouble(item.Element("MonitoringLoss").Value) * 100,
                                        }).ToList<SettingsData>();
                            if (settingsDataList != null && settingsDataList.Count > 0)
                            {
                                FieldData = settingsDataList[0];
                            }
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
            else
            {
                MessageBox.Show("Database connection error while fetching settings data.");
            }
        }

        private void AddtoLayerUnitsDictionary(UnitLayer unitLayer)
        {
            if (layerUnitsDictionary.ContainsKey(unitLayer.layerName))
            {
                List<UnitLayer> l = layerUnitsDictionary[unitLayer.layerName];
                l.Add(unitLayer);
            }
            else
            {
                List<UnitLayer> l = new List<UnitLayer>();
                l.Add(unitLayer);
                layerUnitsDictionary.Add(unitLayer.layerName, l);
            }
        }

        private void GetUnitCapacity()
        {
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_UNIT_CAPACITY_QUERY_ID, null, "UnitCapacity");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForUnitCapacityCompleted);
        }

        void ImportVM_QueryForUnitCapacityCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            if (e.Result != null && e.Error == null)
            {
                if (e.UserState.ToString() == "UnitCapacity")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            List<UnitCapacity> unitCapacityList = (from item in doc.Descendants("Query")
                                                                   select new UnitCapacity
                                                                   {
                                                                       UnitID = Convert.ToInt32(item.Element("Unit_ID").Value),
                                                                       Date = Convert.ToDateTime(item.Element("Date").Value),
                                                                       Capacity = Convert.ToDouble(item.Element("Capacity").Value)
                                                                   }).ToList<UnitCapacity>();
                            foreach (UnitCapacity uc in unitCapacityList)
                            {
                                unitCapacityDictionary.Add(getKeyForStringCapacity(uc.UnitID, uc.Date), uc.Capacity);
                            }

                            isLoadingUnitCapacityCompleted = true;
                            if (isLoadingUnitLayerCompleted == true && importPlans.Count != 0)
                                IsCalButtonEnabled = true;
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                MessageBox.Show("Database connection error while fetching unit capacity data.");
            }
        }

        private string getKeyForStringCapacity(int sUID, DateTime currentDay)
        {
            return sUID.ToString() + currentDay.ToString("yyyyMMdd");
        }

        private void GetUnitsFromDB()
        {
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_UNITS_QUERY_ID, null, "UnitData");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_NewQueryForUnitDataCompleted);
        }

        void ImportVM_NewQueryForUnitDataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            if (e.Result != null && e.Error == null)
            {
                if (e.UserState.ToString() == "UnitData")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            UnitList = (from item in doc.Descendants("Query")
                                        select new Unit
                                        {
                                            UnitID = item.Element("ID") != null ? Convert.ToInt32(item.Element("ID").Value) : 0,
                                            ParentUnitID = item.Element("pID") != null ? Convert.ToInt32(item.Element("pID").Value) : 0,
                                            UnitName = item.Element("uName") != null ? Convert.ToString(item.Element("uName").Value) : string.Empty,
                                            UnitType = item.Element("uType") != null ? Convert.ToString(item.Element("uType").Value) : string.Empty,
                                            FluidType = item.Element("fType") != null ? Convert.ToString(item.Element("fType").Value) : string.Empty,
                                            ProdInjType = item.Element("piType") != null ? Convert.ToString(item.Element("piType").Value) : string.Empty,
                                            Capacity = item.Element("Capacity") != null ? Convert.ToDouble(item.Element("Capacity").Value) : 0
                                        }).ToList<Unit>();


                            List<Unit> duplicateUnitList = new List<Unit>();
                            //init parentUnitList
                            Dictionary<int, Unit> tempUnitDictionary = new Dictionary<int, Unit>();
                            foreach (Unit u in UnitList)
                            {
                                if (tempUnitDictionary.ContainsKey(u.UnitID))
                                {
                                    Unit existUnit = tempUnitDictionary[u.UnitID];
                                    existUnit.ParentUnitIDList.Add(u.ParentUnitID);
                                    existUnit.hasMultipleParent = true;

                                    duplicateUnitList.Add(u);
                                }
                                else
                                {
                                    tempUnitDictionary.Add(u.UnitID, u);
                                    u.ParentUnitIDList.Add(u.ParentUnitID);
                                }
                            }

                            //foreach(Unit du in duplicateUnitList){
                            //    UnitList.Remove(du);
                            //}


                            IsUnitCompleted = true;

                            foreach (Unit unit in UnitList.Where(s => s.UnitName == FIFPConstants.UNITTYPE_MOL && s.UnitType == FIFPConstants.UNITTYPE_PIPELINE))
                            {
                                GetUnitNameList(UnitList.Where(p => p.UnitID == unit.UnitID).ToList(), 0);
                            }

                            foreach (Unit unit in UnitList.Where(s => s.UnitType == FIFPConstants.UNITTYPE_PLATFORM && (s.UnitName == FIFPConstants.PLATFORM_WIP_UNIT || s.UnitName == FIFPConstants.PLATFORM_CP1_UNIT)))
                            {
                                GetUnitNameList(UnitList.Where(p => p.UnitID == unit.UnitID).ToList(), 0);
                            }

                            //foreach (Unit unit in UnitList.Where(s => s.UnitType == FIFPConstants.UNITTYPE_RADIAL))
                            //{
                            //    GetUnitNameList(UnitList.Where(p => p.UnitID == unit.UnitID).ToList(), 0);
                            //}

                            foreach (Unit unit in UnitList.Where(s => s.UnitType == FIFPConstants.UNITTYPE_TOWER && s.FluidType == FIFPConstants.FLUIDTYPE_GAS && s.ParentUnitID == -2))
                            {
                                GetUnitNameList(UnitList.Where(p => p.UnitID == unit.UnitID).ToList(), 0);
                            }


                            if (IsUnitCompleted && CurrentScenarioId > 0)//We have to enable the add activity button once after load unit and any open scenario 
                                IsAddActivityButtonEnabled = true;
                            UnitTypeList.Add(FIFPConstants.SELECT_UNIT_TYPE);
                            SettingsUnitTypeList.Add(FIFPConstants.SELECT_UNIT_TYPE);
                            UnitTypeList.AddRange(UnitList.Select(s => s.UnitType).Distinct().ToList<string>());
                            SourceUnitTypeList.Add(FIFPConstants.SELECT_UNIT_TYPE);
                            SourceUnitTypeList.AddRange(UnitList.Select(s => s.UnitType).Distinct().ToList<string>());
                            SettingsUnitTypeList.AddRange(UnitList.Select(s => s.UnitType).Distinct().ToList<string>());
                            if (UnitTypeList != null && UnitTypeList.Count > 0)
                            {
                                SelectedUnitType = UnitTypeList[0];
                                SettingsSelectedUnitType = UnitTypeList[0];
                            }
                            LoadDefaultValuesForRadialSwitch();

                            if (IsOCCPRadialSwitchSaving)
                            {
                                IsOCCPRadialSwitchSaving = false;
                                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                            }

                            if (IsUnitCompleted)
                                IsInitLoadCompleted = true;

                            //Pass Unitname list to appointment view model
                            if (OnUnitNameListDataCompleted != null)
                                OnUnitNameListDataCompleted(this, null);

                        }
                    }
                    catch (Exception ex)
                    {
                        if (IsOCCPRadialSwitchSaving)
                        {
                            IsOCCPRadialSwitchSaving = false;
                            ServiceLocator.Get<MainPageVM>().IsLoading = false;
                        }
                    }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                MessageBox.Show("Database connection error while fetching unit data.");
            }

        }

        private void LoadDefaultValuesForRadialSwitch()
        {
            RadialSwitchHelper helper = new RadialSwitchHelper();
            helper.USOSSPUnitId = UnitList.Where(s => s.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM).FirstOrDefault().UnitID;
            helper.ByPassUnitId = UnitList.Where(s => s.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL).FirstOrDefault().UnitID;
            helper.OCCPUnitId = UnitList.Where(s => s.UnitName == FIFPConstants.PLATFORM_OCCP_UNIT).FirstOrDefault().UnitID;
            helper.DefaultOCCPRadialList = UnitList.Where(s => s.UnitName == FIFPConstants.PLATFORM_OCCP_UNIT).SelectMany(p => p.ChildUnitList).Select(m => m.UnitID).ToList<int>();
            helper.DefaultBypassRadialList = UnitList.Where(s => s.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL).SelectMany(p => p.ChildUnitList).Select(m => m.UnitID).ToList<int>();


            RadialSwitchDefaultValue = helper;
        }


        private void UnitLayerSelectionChanged(ComboBox cmbUnitLayer)
        {
            if (cmbUnitLayer != null && cmbUnitLayer.SelectedItem != null)
            {
                Layer selectedLayer = cmbUnitLayer.SelectedItem as Layer;
                if (selectedLayer != null && selectedLayer.LayerName != FIFPConstants.SELECT_LAYER)
                {
                    CurrentIPR = SelectedLayer.IPR;
                }
                else
                    CurrentIPR = 0;
            }
        }

        private void UnitLayerMaxProdSelectionChanged(ComboBox cmbMaxProdLayer)
        {
            if (cmbMaxProdLayer != null && cmbMaxProdLayer.SelectedItem != null)
            {
                Layer selectedMaxProdLayer = cmbMaxProdLayer.SelectedItem as Layer;
                if (selectedMaxProdLayer != null && selectedMaxProdLayer.LayerName != FIFPConstants.SELECT_LAYER)
                {
                    CurrentMaxProduction = SelectedMaxProdLayer.MaxProduction;
                }
                else
                    CurrentMaxProduction = 0;
            }
        }


        private void UnitNameSelectionChanged(ComboBox cmbUnitName)
        {
            if (cmbUnitName != null && cmbUnitName.SelectedItem != null)
            {
                Unit selectedUnit = cmbUnitName.SelectedItem as Unit;
                if (selectedUnit != null && selectedUnit.UnitName != FIFPConstants.SELECT_UNITNAME)
                {
                    CurrentCapacity = selectedUnit.Capacity;
                }
                else
                    CurrentCapacity = 0;
            }
        }
        private void SettingsUnitTypeSelectionChanged(ComboBox cmbUnitType1)
        {
            if (cmbUnitType1 != null && cmbUnitType1.SelectedItem != null)
            {
                string selectedUnitType = cmbUnitType1.SelectedItem as string;
                if (!string.IsNullOrEmpty(selectedUnitType) && selectedUnitType != FIFPConstants.SELECT_UNIT_TYPE)
                {
                    List<Unit> unitList = new List<Unit>();
                    unitList.Add(new Unit() { UnitName = FIFPConstants.SELECT_UNITNAME });
                    List<Unit> sortedList = UnitList.Where(u => u.UnitType == selectedUnitType).GroupBy(g => g.UnitName).Select(s => s.First()).ToList<Unit>();
                    sortedList = sortedList.OrderBy(s => s.UnitName).ToList<Unit>();
                    unitList.AddRange(sortedList);
                    SettingsUnitNameList = unitList;
                    if (SettingsUnitNameList != null && SettingsUnitNameList.Count > 0)
                    {
                        IsUnitNameEnabled = true;
                        SettingsSelectedActivityUnit = SettingsUnitNameList[0];
                    }
                }
                else
                {
                    SettingsUnitNameList.Add(new Unit() { UnitName = FIFPConstants.SELECT_UNITNAME });
                    SettingsSelectedActivityUnit = SettingsUnitNameList[0];
                    IsUnitNameEnabled = false;
                }
            }
        }
        private void UnitTypeSelectionChanged(ComboBox cmbUnitType)
        {
            if (cmbUnitType != null && cmbUnitType.SelectedItem != null)
            {
                string selectedUnitType = cmbUnitType.SelectedItem as string;
                if (!string.IsNullOrEmpty(selectedUnitType) && selectedUnitType != FIFPConstants.SELECT_UNIT_TYPE)
                {
                    List<Unit> unitList = new List<Unit>();
                    unitList.Add(new Unit() { UnitName = FIFPConstants.SELECT_UNITNAME });
                    List<Unit> sortedList = UnitList.Where(u => u.UnitType == selectedUnitType).GroupBy(g => g.UnitName).Select(s => s.First()).ToList<Unit>();
                    sortedList = sortedList.OrderBy(s => s.UnitName).ToList<Unit>();
                    unitList.AddRange(sortedList);
                    UnitNameList = unitList;
                    if (UnitNameList != null && UnitNameList.Count > 0)
                    {
                        IsUnitNameEnabled = true;
                        SelectedActivityUnit = UnitNameList[0];
                    }
                }
                else
                {
                    UnitNameList.Add(new Unit() { UnitName = FIFPConstants.SELECT_UNITNAME });
                    SelectedActivityUnit = UnitNameList[0];
                    IsUnitNameEnabled = false;
                }
            }
        }

        private void LoadUnitTypeByActivityCode(ComboBox cmbActivityCode)
        {
            if (SelectedActivityCode != null && SelectedActivityCode.Name != FIFPConstants.SELECT_ACTIVITY)
            {
                if (SelectedActivityCode.Name == FIFPConstants.ACTIVITY_TYPE_MTN_SS)
                    UnitTypeList = SourceUnitTypeList.Where(unitType => unitType == FIFPConstants.UNITTYPE_PIPELINE || unitType == FIFPConstants.UNITTYPE_RADIAL || unitType == FIFPConstants.SELECT_UNIT_TYPE).ToList<string>();
                else if (SelectedActivityCode.Name == FIFPConstants.ACTIVITY_TYPE_PIG_IP || SelectedActivityCode.Name == FIFPConstants.ACTIVITY_TYPE_PIG_CL)
                    UnitTypeList = SourceUnitTypeList.Where(unitType => unitType == FIFPConstants.UNITTYPE_PIPELINE || unitType == FIFPConstants.UNITTYPE_RADIAL || unitType == FIFPConstants.SELECT_UNIT_TYPE).ToList<string>();
                else if (SelectedActivityCode.Name == FIFPConstants.ACTIVITY_TYPE_INSP_F)
                    UnitTypeList = SourceUnitTypeList.Where(unitType => unitType != FIFPConstants.UNITTYPE_PIPELINE && unitType != FIFPConstants.UNITTYPE_RADIAL && unitType != FIFPConstants.UNITTYPE_WELL && unitType != FIFPConstants.UNITTYPE_STRING).ToList<string>();
                else if (SelectedActivityCode.Name == FIFPConstants.ACTIVITY_TYPE_HKP)
                    UnitTypeList = SourceUnitTypeList.Where(unitType => unitType == FIFPConstants.UNITTYPE_WELL || unitType == FIFPConstants.UNITTYPE_STRING || unitType == FIFPConstants.SELECT_UNIT_TYPE).ToList<string>();
                else if (SelectedActivityCode.Name == FIFPConstants.ACTIVITY_TYPE_RIG || SelectedActivityCode.Name == FIFPConstants.ACTIVITY_TYPE_RGL)
                    UnitTypeList = SourceUnitTypeList.Where(unitType => unitType == FIFPConstants.UNITTYPE_TOWER || unitType == FIFPConstants.UNITTYPE_WELL || unitType == FIFPConstants.SELECT_UNIT_TYPE).ToList<string>();
                else if (SelectedActivityCode.Name == FIFPConstants.ACTIVITY_TYPE_MON)
                    UnitTypeList = SourceUnitTypeList.Where(unitType => unitType == FIFPConstants.UNITTYPE_WELL || unitType == FIFPConstants.UNITTYPE_STRING || unitType == FIFPConstants.SELECT_UNIT_TYPE).ToList<string>();
                else
                    UnitTypeList = SourceUnitTypeList;

                SelectedUnitType = UnitTypeList[0];
                IsUnitTypeEnabled = true;
            }
            else
            {
                SelectedUnitType = UnitTypeList[0];
                IsUnitTypeEnabled = false;
            }
        }

        private void LoadActivityByDivision(ComboBox cmbDivision)
        {
            if (SelectedDivisionName != null && SelectedDivisionName.Name != FIFPConstants.SELECT_DIVISION)
            {
                List<ActivityType> activityList = new List<ActivityType>();
                activityList.Add(new ActivityType() { Name = FIFPConstants.SELECT_ACTIVITY });
                activityList.AddRange(ActivityCodeDivisionList.Where(s => s.Type == "a" && s.ActivityStatus != "Open" && s.DivisionId == SelectedDivisionName.Id).ToList<ActivityType>());
                ActivityCodeList = activityList;
                if (ActivityCodeList != null && ActivityCodeList.Count > 0)
                {
                    IsActivityCodeEnabled = true;
                    SelectedActivityCode = ActivityCodeList[0];
                }
            }
            else
            {
                SelectedActivityCode = ActivityCodeList[0];
                IsActivityCodeEnabled = false;

            }
        }
        void activityPopup_Closed(object sender, EventArgs e)
        {
            IsAddActivityButtonEnabled = true;
        }


        void ImportVM_OnImportClick(object sender, EventArgs e)
        {
            //LoadUnitTypeFacilityList();
            ImportPlans.ForEach(s => { s.ActivityLevel = 1; });//Undo only page level
            ServiceLocator.Get<AppointmentVM>().RadScheduleViewDragDropBehavior = new ScheduleDragDropBehavior();
            ServiceLocator.Get<FilterVM>().IsDivisionEnabled = true;
            LoadTimelineView((from item in ScheduleViewAppointments orderby item.nIndex ascending select item).ToList<FIFPAppointment>());
        }

        private void LoadUnitTypeFacilityList()
        {
            List<FilterData> unitTypeList = new List<FilterData>(ServiceLocator.Get<FilterVM>().UnitTypeList);
            unitTypeList.ForEach(s => { s.ItemVisibility = Visibility.Visible; });
            ServiceLocator.Get<FilterVM>().UnitTypeList = new ObservableCollection<FilterData>(unitTypeList);

            List<FilterData> facilityList = new List<FilterData>(ServiceLocator.Get<FilterVM>().FacilityList);
            facilityList.ForEach(s => { s.ItemVisibility = Visibility.Visible; });
            ServiceLocator.Get<FilterVM>().FacilityList = new ObservableCollection<FilterData>(facilityList);
        }
        #endregion

        private void CancelAdminSettings(Button sender)
        {
            if (_validationResults.Count > 0)
                _validationResults.Clear();
            IsAnimationStarted = false;
            BValidate = false;
            StoryboardManager.PlayStoryboard(FIFPConstants.SETTINGSFLIP_STOP, s => { }, null);
        }

        #region Load Textboxes
        TextBox txtCapacity = null;
        TextBox txtIPR = null;
        TextBox txtMaxProd = null;
        TextBox txtUPL = null;
        TextBox txtMonitoring = null;
        private void LoadCapacityTextBox(TextBox txtBox)
        {
            txtCapacity = txtBox;
        }
        private void LoadIPRTextBox(TextBox txtBox)
        {
            txtIPR = txtBox;
        }
        private void LoadMaxProdTextBox(TextBox txtBox)
        {
            txtMaxProd = txtBox;
        }

        private void LoadUnplannedTextBox(TextBox txtBox)
        {
            txtUPL = txtBox;
        }
        private void LoadMonitoringTextBox(TextBox txtBox)
        {
            txtMonitoring = txtBox;
        }
        #endregion

        private void SubmitAdminSettings(Button sender)
        {
            //Settings Save logic
            BValidate = true;
            if (CheckSettingsValidation())
            {
                BValidate = false;
                SaveSettingsDataIntoDB();
            }
        }

        private void SaveSettingsDataIntoDB()
        {
            //SelectedLayer.LayerID, FIFPConstants.FIELD_NAME, NewIPR, NewUnplannedLossesPercentage, NewMonitoringPercentage, SelectedActivityUnit.UnitID, NewCapacity
            double newCapacity = 0; double newIPR = 0; double newMaxProd = 0; double newPlanPercentage = 0; double newMonitorPercentage = 0;
            if (NewCapacity == string.Empty)
                newCapacity = SettingsSelectedActivityUnit.Capacity;
            else
            {
                newCapacity = Convert.ToDouble(NewCapacity);
                CurrentCapacity = newCapacity;
                SettingsSelectedActivityUnit.Capacity = newCapacity;
            }

            if (NewIPR == string.Empty)
                newIPR = FieldData.IPR;
            else
            {
                newIPR = Convert.ToDouble(NewIPR);
                CurrentIPR = newIPR;
                SelectedLayer.IPR = newIPR;
            }


            if (NewMaxProduction == string.Empty)
                newMaxProd = FieldData.CurrentMaxProd;
            else
            {
                newMaxProd = Convert.ToDouble(NewMaxProduction);
                CurrentMaxProduction = newMaxProd;
                SelectedMaxProdLayer.MaxProduction = newMaxProd;
            }


            if (NewUnplannedLossesPercentage == string.Empty)
                newPlanPercentage = Math.Round(Convert.ToDouble(FieldData.CurrentUnplannedLossesPercentage) / 100, 4);
            else
            {
                newPlanPercentage = !string.IsNullOrEmpty(NewUnplannedLossesPercentage) ? Math.Round(Convert.ToDouble(NewUnplannedLossesPercentage) / 100, 4) : 0;
                FieldData.CurrentUnplannedLossesPercentage = Convert.ToDouble(NewUnplannedLossesPercentage);
            }

            if (NewMonitoringPercentage == string.Empty)
                newMonitorPercentage = Math.Round(Convert.ToDouble(FieldData.CurrentMonitoringPercentage) / 100, 4);
            else
            {
                newMonitorPercentage = !string.IsNullOrEmpty(NewMonitoringPercentage) ? Math.Round(Convert.ToDouble(NewMonitoringPercentage) / 100, 4) : 0;
                FieldData.CurrentMonitoringPercentage = Convert.ToDouble(NewMonitoringPercentage);
            }

            string[] param = new string[] { Convert.ToString(SelectedLayer.LayerID), FIFPConstants.FIELD_NAME, Convert.ToString(newIPR), Convert.ToString(newPlanPercentage), Convert.ToString(newMonitorPercentage), Convert.ToString(SettingsSelectedActivityUnit.UnitID), Convert.ToString(newCapacity), Convert.ToString(newMaxProd), Convert.ToString(SelectedMaxProdLayer.LayerID) };
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.INSERT_SETTINGS_QUERY_ID, param, "InsertSettingsData");
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_NewQueryForInsertSettingsDataCompleted);

            SaveAdminOCCPRadialSwitch();
        }

        private void SaveAdminOCCPRadialSwitch()
        {
            string[] param = null;
            string strUnits = string.Empty;

            List<Unit> lstOCCPModifiedUnits = OccpRadialFlowList.Where(s => s.IsModified == 0 && s.USOSSPItemChecked == true).ToList<Unit>();
            if (lstOCCPModifiedUnits != null && lstOCCPModifiedUnits.Count > 0)
            {

                foreach (Unit unit in lstOCCPModifiedUnits)
                {
                    if (unit.IsModified == 0)//2 parameters(UnitId , ParentUnitId)
                        strUnits += unit.UnitID.ToString() + "|" + RadialSwitchDefaultValue.OCCPUnitId + "|";
                }
            }

            List<Unit> lstByPassModifiedUnits = OccpRadialFlowList.Where(s => s.IsModified == 0 && s.ByPassItemChecked == true).ToList<Unit>();
            if (lstByPassModifiedUnits != null && lstByPassModifiedUnits.Count > 0)
            {

                foreach (Unit unit in lstByPassModifiedUnits)
                {
                    if (unit.IsModified == 0)//2 parameters(UnitId , ParentUnitId)
                        strUnits += unit.UnitID.ToString() + "|" + RadialSwitchDefaultValue.ByPassUnitId + "|";
                }
            }
            if (!string.IsNullOrEmpty(strUnits))
            {
                IsOCCPRadialSwitchSaving = true;
                param = new string[] { strUnits.TrimEnd('|') };
                ServiceLocator.Get<MainPageVM>().IsLoading = true;
                ServiceLocator.Get<MainPageVM>().LoadingMessage = FIFPConstants.LOADING_SAVERADIAL_SWITCH_MESSAGE;
                RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
                queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_Save_ADMIN_SWITCHEDRADIAL_QUERY_ID, param, "SaveAdminRadialSwitch");
                queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForSaveUpdateRS_DataCompleted);
            }
        }

        void ImportVM_QueryForSaveUpdateRS_DataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            if (e.Result != null && e.Error == null)
            {
                if (e.UserState.ToString() == "SaveAdminRadialSwitch")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                        }
                        foreach (Unit unit in OccpRadialFlowList)
                            unit.IsModified = -1;
                        GetUnitsFromDB();
                    }
                    catch (Exception ex)
                    { }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
            }

        }

        void ImportVM_NewQueryForInsertSettingsDataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UserState.ToString() == "InsertSettingsData")
                {
                    try
                    {

                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                        }
                        if (IsAnimationStarted)
                        {
                            IsAnimationStarted = false;
                            StoryboardManager.PlayStoryboard(FIFPConstants.SETTINGSFLIP_STOP, s => { }, null);
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
            }

        }

        private bool CheckSettingsValidation()
        {
            bool bRet = true;
            bool bPercentageValidation = true;
            BPercentageValidate = false;
            NewCapacity = txtCapacity.Text.Trim();
            if (!string.IsNullOrEmpty(NewCapacity))
            {
                bool isCapacityOk = true;
                if (!Regex.IsMatch(NewCapacity, FIFPConstants.RegularExpression))
                {
                    bRet = false;
                    isCapacityOk = false;
                    txtCapacity.Focus();
                    NotifyPropertyChanged(() => NewCapacity);
                }
                if (isCapacityOk)
                {
                    NotifyPropertyChanged(() => NewCapacity);
                    if (SettingsSelectedUnitType == FIFPConstants.SELECT_UNIT_TYPE)
                    {
                        bRet = false;
                        NotifyPropertyChanged(() => SettingsSelectedUnitType);
                    }
                    if (IsUnitNameEnabled && SettingsSelectedActivityUnit.UnitName == FIFPConstants.SELECT_UNITNAME)
                    {
                        bRet = false;
                        NotifyPropertyChanged(() => SettingsSelectedActivityUnit);
                    }
                }
            }

            NewIPR = txtIPR.Text.Trim();
            if (!string.IsNullOrEmpty(NewIPR))
            {
                bool isIPROk = true;
                if (!Regex.IsMatch(NewIPR, FIFPConstants.RegularExpression))
                {
                    bRet = false;
                    isIPROk = false;
                    txtIPR.Focus();
                    NotifyPropertyChanged(() => NewIPR);
                }
                else if (!string.IsNullOrEmpty(Convert.ToString(NewIPR)) && (Convert.ToDouble(NewIPR) < 0 || Convert.ToDouble(NewIPR) > 3))
                {
                    bRet = false;
                    isIPROk = false;
                    txtIPR.Focus();
                    NotifyPropertyChanged(() => NewIPR);
                }
                if (isIPROk)
                {
                    NotifyPropertyChanged(() => NewIPR);
                    if (SelectedLayer.LayerName == FIFPConstants.SELECT_LAYER)
                    {
                        bRet = false;
                        NotifyPropertyChanged(() => SelectedLayer);
                    }
                }
            }


            NewMaxProduction = txtMaxProd.Text.Trim();
            if (!string.IsNullOrEmpty(NewMaxProduction))
            {
                bool isMaxProdOk = true;
                if (!Regex.IsMatch(NewMaxProduction, FIFPConstants.RegularExpression))
                {
                    bRet = false;
                    isMaxProdOk = false;
                    txtMaxProd.Focus();
                    NotifyPropertyChanged(() => NewMaxProduction);
                }
                else if (!string.IsNullOrEmpty(Convert.ToString(NewMaxProduction)) && Convert.ToDouble(NewMaxProduction) < 0)
                {
                    bRet = false;
                    isMaxProdOk = false;
                    txtMaxProd.Focus();
                    NotifyPropertyChanged(() => NewMaxProduction);
                }
                if (isMaxProdOk)
                {
                    NotifyPropertyChanged(() => NewMaxProduction);
                    if (SelectedMaxProdLayer.LayerName == FIFPConstants.SELECT_LAYER)
                    {
                        bRet = false;
                        NotifyPropertyChanged(() => SelectedMaxProdLayer);
                    }
                }
            }

            NewUnplannedLossesPercentage = txtUPL.Text.Trim();
            if (!string.IsNullOrEmpty(NewUnplannedLossesPercentage))
            {

                if (!Regex.IsMatch(NewUnplannedLossesPercentage, FIFPConstants.RegularExpression))
                {
                    bRet = false;
                    bPercentageValidation = false;
                    txtUPL.Focus();
                    NotifyPropertyChanged(() => NewUnplannedLossesPercentage);
                }
                else if (!string.IsNullOrEmpty(Convert.ToString(NewUnplannedLossesPercentage)) && (Convert.ToDouble(NewUnplannedLossesPercentage) < 0 || Convert.ToDouble(NewUnplannedLossesPercentage) > 100))
                {
                    bRet = false;
                    bPercentageValidation = false;
                    txtUPL.Focus();
                    NotifyPropertyChanged(() => NewUnplannedLossesPercentage);
                }
                else if (!string.IsNullOrEmpty(Convert.ToString(NewUnplannedLossesPercentage)) && (Convert.ToDouble(NewUnplannedLossesPercentage) + FieldData.CurrentMonitoringPercentage) > 100)
                {
                    bRet = false;
                    bPercentageValidation = false;
                    BPercentageValidate = true;
                    txtUPL.Focus();
                    NotifyPropertyChanged(() => NewUnplannedLossesPercentage);
                }
                else
                {
                    bRet = true;
                    bPercentageValidation = true;
                    NotifyPropertyChanged(() => NewUnplannedLossesPercentage);
                }
            }

            NewMonitoringPercentage = txtMonitoring.Text.Trim();
            if (!string.IsNullOrEmpty(NewMonitoringPercentage))
            {
                if (!Regex.IsMatch(NewMonitoringPercentage, FIFPConstants.RegularExpression))
                {
                    bRet = false;
                    bPercentageValidation = false;
                    txtMonitoring.Focus();
                    NotifyPropertyChanged(() => NewMonitoringPercentage);
                }
                else if (!string.IsNullOrEmpty(Convert.ToString(NewMonitoringPercentage)) && (Convert.ToDouble(NewMonitoringPercentage) < 0 || Convert.ToDouble(NewMonitoringPercentage) > 100))
                {
                    bRet = false;
                    bPercentageValidation = false;
                    txtMonitoring.Focus();
                    NotifyPropertyChanged(() => NewMonitoringPercentage);
                }
                else if (!string.IsNullOrEmpty(Convert.ToString(NewMonitoringPercentage)) && (Convert.ToDouble(NewMonitoringPercentage) + FieldData.CurrentUnplannedLossesPercentage) > 100)
                {
                    bRet = false;
                    bPercentageValidation = false;
                    BPercentageValidate = true;
                    txtUPL.Focus();
                    NotifyPropertyChanged(() => NewMonitoringPercentage);
                }
                else
                {
                    bRet = true;
                    bPercentageValidation = true;
                    NotifyPropertyChanged(() => NewMonitoringPercentage);
                }
            }


            if (bPercentageValidation && !string.IsNullOrEmpty(NewUnplannedLossesPercentage) && !string.IsNullOrEmpty(NewMonitoringPercentage))
            {
                double percentage = Math.Round(Convert.ToDouble(NewUnplannedLossesPercentage) / 100, 4) + Math.Round(Convert.ToDouble(NewMonitoringPercentage) / 100, 4);
                if (percentage > 1)
                {
                    bRet = false;
                    BPercentageValidate = true;
                    txtMonitoring.Focus();
                    NotifyPropertyChanged(() => NewMonitoringPercentage);
                }
                else
                {
                    bRet = true;
                    BPercentageValidate = false;
                    txtMonitoring.Focus();
                    NotifyPropertyChanged(() => NewMonitoringPercentage);
                }
            }

            return bRet;
        }
        private void ShowAdminSettings(HyperlinkButton sender)
        {
            //TODO Logic
            ResetFields();
            BValidate = false;
            OccpRadialFlowList = new List<Unit>();

            List<Unit> OCCPRadialList = UnitList.Where(s => s.UnitName == FIFPConstants.PLATFORM_OCCP_UNIT).SelectMany(p => p.ChildUnitList).ToList<Unit>();
            OCCPRadialList.ForEach(s => { s.USOSSPItemChecked = true; });
            List<Unit> BypassRadialList = UnitList.Where(s => s.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL).SelectMany(p => p.ChildUnitList).ToList<Unit>();
            BypassRadialList.ForEach(s => { s.ByPassItemChecked = true; });
            List<Unit> USOSSPList = new List<Unit>();
            USOSSPList.AddRange(OCCPRadialList);
            USOSSPList.AddRange(BypassRadialList);
            int nIndex = 0;
            foreach (Unit unit in USOSSPList)
            {
                unit.GroupId = nIndex;
                nIndex++;
            }

            OccpRadialFlowList = USOSSPList;
            StoryboardManager.PlayStoryboard(FIFPConstants.SETTINGSFLIP_START, s => { }, null);
            IsAnimationStarted = true;
        }

        private void OCCPRadialSwitchChecked(RadioButton radioBtn)
        {
            if (radioBtn != null && radioBtn.Tag != null)
            {
                Unit occpUnit = radioBtn.Tag as Unit;
                if (occpUnit != null)
                {
                    occpUnit.IsModified = 0;
                }
            }
        }

        #region Get Treeview UnitList
        private void GetUnitNameList(List<Unit> lstUnits, int level)
        {
            foreach (Unit unit in lstUnits)
            {
                unit.Level = level;
                unit.ChildUnitList = UnitList.Where(p => p.ParentUnitID == unit.UnitID).ToList();
                GetUnitNameList(unit.ChildUnitList, level + 1);
            }
        }
        #endregion

        #region Make database call to get appointments
        private void LoadappointmentsFromDB(Grid layoutRoot)
        {
            if (ImportPlans != null && ImportPlans.Count == 0)
            {
                AppointmentGroup appointmentGroup = new AppointmentGroup();
                appointmentGroup.Appointments = new List<FIFPAppointment>() { new FIFPAppointment() { Subject = "ADMA" } };

                if (OnAppointmentDataCompleted != null)
                    OnAppointmentDataCompleted(this, new CustomEventArgs<AppointmentGroup>(appointmentGroup));
            }
        }
        #endregion

        #region Create QueryClient Instance
        /*
        public RelationalDataServiceClient CreateQueryClientInstance()
        {
            if (queryClient == null)
            {
                queryClient = new RelationalDataServiceClient();
            }
            return queryClient;
        }*/
        #endregion

        #region Load Appointments

        void ImportVM_QueryForDataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            IsAddActivityButtonEnabled = true;
            IsCalButtonEnabled = true;
            if (e.Result != null && e.Error == null)
            {
                if (Convert.ToString(e.UserState) == "OpenScenario")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);
                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            ParseScenarioPlansXml(doc);
                            if (ImportPlans != null && ImportPlans.Count > 0)//Scenario plans there in the Database
                            {
                                CurrentScenarioId = ImportPlans[0].ScenarioId;
                                GetReducedCapacityFromDB();//Call this function once we get the plans from database bcoz we need to pass scenarioId
                                GetSwitchedRadialFromDB();
                                ServiceLocator.Get<MainPageVM>().IsScenarioCompareEnabled = true;

                                //ServiceLocator.Get<MainPageVM>().IsIntegrationEnabled = true;
                                //BindData();

                                //if (IsUnitCompleted && CurrentScenarioId > 0) //We have to enable the add activity button once after load unit and any open scenario 
                                //    IsAddActivityButtonEnabled = true;
                                //if (isLoadingUnitCapacityCompleted == true && isLoadingUnitLayerCompleted == true)
                                //    IsCalButtonEnabled = true;
                            }
                            else
                            {
                                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                                if (ImportPlans != null && ImportPlans.Count > 0)
                                    ImportPlans.Clear();
                                LoadTimelineView((from item in ImportPlans orderby item.nIndex ascending select item).ToList<FIFPAppointment>());
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        ServiceLocator.Get<MainPageVM>().IsLoading = false;
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                MessageBox.Show("Database connection error when opening scenario.");
            }
        }

        private void ParseScenarioPlansXml(XDocument doc)
        {
            var items = from item in doc.Descendants("Query")
                        select new FIFPAppointment
                        {
                            PlanID = item.Element("id") != null ? Convert.ToInt32(item.Element("id").Value) : 0,
                            ScenarioId = item.Element("sid") != null ? Convert.ToInt32(item.Element("sid").Value) : 0,
                            UnitID = item.Element("uid") != null ? Convert.ToInt32(item.Element("uid").Value) : 0,
                            UnitName = item.Element("uname") != null ? Convert.ToString(item.Element("uname").Value) : string.Empty,
                            UnitType = item.Element("utype") != null ? Convert.ToString(item.Element("utype").Value) : string.Empty,
                            Division = item.Element("dname") != null ? Convert.ToString(item.Element("dname").Value) : string.Empty,
                            ActivityCode = item.Element("acode") != null ? Convert.ToString(item.Element("acode").Value) : string.Empty,
                            ActivityId = item.Element("activityId") != null ? Convert.ToInt32(item.Element("activityId").Value) : 0,
                            Subject = item.Element("acode") != null ? Convert.ToString(item.Element("acode").Value) : string.Empty,
                            ActivityCodeDescription = item.Element("ActivityCodeDescription") != null ? Convert.ToString(item.Element("ActivityCodeDescription").Value) : string.Empty,
                            FluidType = item.Element("ftype") != null ? Convert.ToString(item.Element("ftype").Value) : string.Empty,
                            Start = item.Element("sdate") != null ? Convert.ToDateTime(item.Element("sdate").Value) : DateTime.MinValue,
                            ModifiedStart = item.Element("sdate") != null ? Convert.ToDateTime(item.Element("sdate").Value) : DateTime.MinValue,
                            OriginalStart = item.Element("ostart") != null ? Convert.ToDateTime(item.Element("ostart").Value) : DateTime.MinValue,
                            End = item.Element("edate") != null ? Convert.ToDateTime(item.Element("edate").Value) : DateTime.MinValue,
                            ModifiedEnd = item.Element("edate") != null ? Convert.ToDateTime(item.Element("edate").Value) : DateTime.MinValue,
                            OriginalEnd = item.Element("oend") != null ? Convert.ToDateTime(item.Element("oend").Value) : DateTime.MinValue,
                            Remarks = item.Element("ActivityDescription") != null ? Convert.ToString(item.Element("ActivityDescription").Value) : string.Empty,
                            DB_Remarks = item.Element("ActivityDescription") != null ? Convert.ToString(item.Element("ActivityDescription").Value) : string.Empty,
                            UnitStatus = item.Element("astatus") != null ? Convert.ToString(item.Element("astatus").Value) : string.Empty,
                            CapacityPercentage = item.Element("Percentage") != null ? Convert.ToDouble(item.Element("Percentage").Value) : 1,
                            ReducedCapacity = item.Element("ReducedCapacity") != null ? Convert.ToDouble(item.Element("ReducedCapacity").Value) : 0,
                            LSDDeletedIds = item.Element("LSDUnitId") != null ? Convert.ToString(item.Element("LSDUnitId").Value) : string.Empty,
                            SelectedOilString = item.Element("CTString") != null ? Convert.ToString(item.Element("CTString").Value) : string.Empty,
                            IsAppliedSimops = item.Element("IsOverlap_ApplySIMOP") != null ? Convert.ToBoolean(item.Element("IsOverlap_ApplySIMOP").Value) : false,
                            IsAppliedLSDSimops = item.Element("IsLSD_ApplySIMOP") != null ? Convert.ToBoolean(item.Element("IsLSD_ApplySIMOP").Value) : false,
                            IsAppliedCrossingLine = item.Element("IsLSD_CrossingLine") != null ? Convert.ToBoolean(item.Element("IsLSD_CrossingLine").Value) : false,
                            DB_OverlapId = item.Element("OverlapId") != null ? Convert.ToInt32(item.Element("OverlapId").Value) : 0,
                            IsRDVisibility = item.Element("IsRDVisibility") != null ? Convert.ToBoolean(item.Element("IsRDVisibility").Value) : false,
                            IsOverlapRemoved = item.Element("IsOverlapRemoved") != null ? Convert.ToBoolean(item.Element("IsOverlapRemoved").Value) : false,
                        };
            ScenarioPlans = items.ToList<FIFPAppointment>();
            foreach (FIFPAppointment appointment in ScenarioPlans)
            {
                appointment.ModificationReason = appointment.IsOverlapRemoved ? FIFPConstants.OVERLAP_REMOVE_TEXT : string.Empty;
                appointment.nIndex = (appointment.UnitName == FIFPConstants.UNITTYPE_MOL && appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 1 : (appointment.UnitType == FIFPConstants.UNITTYPE_USSC_PLATFORM) ? 2 : (appointment.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL && appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 3 : (appointment.UnitType == FIFPConstants.UNITTYPE_PLATFORM) ? 4 : (appointment.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR) ? 5 : (appointment.UnitType == FIFPConstants.UNITTYPE_SEPERATOR) ? 6 : (appointment.UnitType == FIFPConstants.UNITTYPE_MODULE) ? 7 : (appointment.UnitType == FIFPConstants.UNITTYPE_SPHEROID) ? 8 : (appointment.UnitType == FIFPConstants.UNITTYPE_STRIPPER) ? 9 : (appointment.UnitType == FIFPConstants.UNITTYPE_RADIAL) ? 10 : (appointment.UnitType == FIFPConstants.UNITTYPE_TOWER) ? 11 : (appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 12 : (appointment.UnitType == FIFPConstants.UNITTYPE_WELL) ? 13 : (appointment.UnitType == FIFPConstants.UNITTYPE_STRING ? 14 : 0);
                //if (appointment.Start == appointment.End)
                {
                    appointment.Start = new DateTime(appointment.Start.Year, appointment.Start.Month, appointment.Start.Day, 0, 0, 0);
                    appointment.End = new DateTime(appointment.End.Year, appointment.End.Month, appointment.End.Day, 23, 59, 59);
                    appointment.OriginalStart = new DateTime(appointment.Start.Year, appointment.Start.Month, appointment.Start.Day, 0, 0, 0);
                    appointment.OriginalEnd = new DateTime(appointment.End.Year, appointment.End.Month, appointment.End.Day, 23, 59, 59);
                    appointment.ModifiedStart = new DateTime(appointment.Start.Year, appointment.Start.Month, appointment.Start.Day, 0, 0, 0);
                    appointment.ModifiedEnd = new DateTime(appointment.End.Year, appointment.End.Month, appointment.End.Day, 23, 59, 59);
                }
                SetClosedStringForCombinedTower(appointment);
            }
            GenerateLinkedShutdownPlans(ScenarioPlans);
            ImportPlans = items.ToList<FIFPAppointment>();
            GenerateLinkedShutdownPlans(ImportPlans);
            if (ImportPlans != null && ImportPlans.Count > 0)
            {
                foreach (FIFPAppointment appointment in ImportPlans)
                {
                    appointment.ModificationReason = appointment.IsOverlapRemoved ? FIFPConstants.OVERLAP_REMOVE_TEXT : string.Empty;
                    appointment.nIndex = (appointment.UnitName == FIFPConstants.UNITTYPE_MOL && appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 1 : (appointment.UnitType == FIFPConstants.UNITTYPE_USSC_PLATFORM) ? 2 : (appointment.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL && appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 3 : (appointment.UnitType == FIFPConstants.UNITTYPE_PLATFORM) ? 4 : (appointment.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR) ? 5 : (appointment.UnitType == FIFPConstants.UNITTYPE_SEPERATOR) ? 6 : (appointment.UnitType == FIFPConstants.UNITTYPE_MODULE) ? 7 : (appointment.UnitType == FIFPConstants.UNITTYPE_SPHEROID) ? 8 : (appointment.UnitType == FIFPConstants.UNITTYPE_STRIPPER) ? 9 : (appointment.UnitType == FIFPConstants.UNITTYPE_RADIAL) ? 10 : (appointment.UnitType == FIFPConstants.UNITTYPE_TOWER) ? 11 : (appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 12 : (appointment.UnitType == FIFPConstants.UNITTYPE_WELL) ? 13 : (appointment.UnitType == FIFPConstants.UNITTYPE_STRING ? 14 : 0);
                    //if (appointment.Start == appointment.End)
                    {
                        appointment.Start = new DateTime(appointment.Start.Year, appointment.Start.Month, appointment.Start.Day, 0, 0, 0);
                        appointment.End = new DateTime(appointment.End.Year, appointment.End.Month, appointment.End.Day, 23, 59, 59);
                        appointment.OriginalStart = new DateTime(appointment.Start.Year, appointment.Start.Month, appointment.Start.Day, 0, 0, 0);
                        appointment.OriginalEnd = new DateTime(appointment.End.Year, appointment.End.Month, appointment.End.Day, 23, 59, 59);
                        appointment.ModifiedStart = new DateTime(appointment.Start.Year, appointment.Start.Month, appointment.Start.Day, 0, 0, 0);
                        appointment.ModifiedEnd = new DateTime(appointment.End.Year, appointment.End.Month, appointment.End.Day, 23, 59, 59);
                    }
                    SetClosedStringForCombinedTower(appointment);
                }
                ServiceLocator.Get<FilterVM>().StartDate = (ImportPlans != null && ImportPlans.Count > 0) ? ImportPlans.Min(s => s.Start) : new DateTime(DateTime.Now.Year, 1, 1, 0, 0, 0);
                ServiceLocator.Get<FilterVM>().EndDate = (ImportPlans != null && ImportPlans.Count > 0) ? ImportPlans.Max(s => s.End) : new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59);
            }
        }

        private void SetClosedStringForCombinedTower(FIFPAppointment appointment)
        {
            if (appointment.SelectedOilString == FIFPConstants.SHUTDOWN_CLOSEDSTRING_ALLSTRINGS)
                appointment.LsdPlans.ForEach(s => { s.IsLinkedShutdownPlan = true; s.SelectedString = appointment.SelectedOilString; });//Selected activity contains default unit shutdown strings
            else if (appointment.SelectedOilString == FIFPConstants.SHUTDOWN_CLOSEDSTRING_OILSTRINGS)
            {
                appointment.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = true; });
                appointment.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = false; });
            }
            else if (appointment.SelectedOilString == FIFPConstants.SHUTDOWN_CLOSEDSTRING_WATERSTRINGS)
            {
                appointment.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_WATER).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = true; });
                appointment.LsdPlans.Where(s => s.FluidType == FIFPConstants.FLUIDTYPE_OIL).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = false; });
            }
        }
        private void BindData()
        {
            foreach (FIFPAppointment appointment in ImportPlans)
            {
                appointment.nIndex = (appointment.UnitName == FIFPConstants.UNITTYPE_MOL && appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 1 : (appointment.UnitType == FIFPConstants.UNITTYPE_USSC_PLATFORM) ? 2 : (appointment.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL && appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 3 : (appointment.UnitType == FIFPConstants.UNITTYPE_PLATFORM) ? 4 : (appointment.UnitType == FIFPConstants.UNITTYPE_COMPRESSOR) ? 5 : (appointment.UnitType == FIFPConstants.UNITTYPE_SEPERATOR) ? 6 : (appointment.UnitType == FIFPConstants.UNITTYPE_MODULE) ? 7 : (appointment.UnitType == FIFPConstants.UNITTYPE_SPHEROID) ? 8 : (appointment.UnitType == FIFPConstants.UNITTYPE_STRIPPER) ? 9 : (appointment.UnitType == FIFPConstants.UNITTYPE_RADIAL) ? 10 : (appointment.UnitType == FIFPConstants.UNITTYPE_TOWER) ? 11 : (appointment.UnitType == FIFPConstants.UNITTYPE_PIPELINE) ? 12 : (appointment.UnitType == FIFPConstants.UNITTYPE_WELL) ? 13 : (appointment.UnitType == FIFPConstants.UNITTYPE_STRING ? 14 : 0);
                if (appointment.FluidType == FIFPConstants.FLUIDTYPE_COMBINED)//Set default is OW
                    appointment.CombinedTowerLSDType = FIFPConstants.FLUIDTYPE_COMBINED;
            }

            if (SelectedScenarioId > 0)// This is no need. We have to remove it in Future 
            {
                Scenario scenario = ScenarioList.Where(s => s.ScenarioId == SelectedScenarioId).FirstOrDefault();
                if (scenario != null)
                    ImportPlans.ForEach(f => { f.ScenarioId = SelectedScenarioId; f.ScenarioName = scenario.ScenarioName; f.ScenarioDescription = scenario.ScenarioDescription; });
            }

            ServiceLocator.Get<FilterVM>().IsDivisionEnabled = true;
            ServiceLocator.Get<FilterVM>().IsFilterEnabled = true;
            IsFilterButtonEnabled = true;
            LoadTimelineView((from item in ImportPlans orderby item.nIndex ascending select item).ToList<FIFPAppointment>());
        }

        #endregion

        #region LoadTimelineView
        public void LoadTimelineView(List<FIFPAppointment> plans)
        {
            ScheduleViewAppointments = plans;
            AppointmentGroup appointmentGroup = new AppointmentGroup();
            List<ResourceType> lstResources = new List<ResourceType>();
            List<Resource> unitList = new List<Resource>();
            ResourceType unitType = new ResourceType("Unit");
            unitType.DisplayName = "Unit";
            unitType.Name = "Unit";

            foreach (FIFPAppointment appointment in plans)
            {
                Resource resource = new Resource() { ResourceName = appointment.UnitName, DisplayName = appointment.UnitName, ResourceType = unitType.Name };
                //unitList.Add(resource);
                if (!unitList.Contains(resource))
                {
                    unitList.Add(resource);
                }
                appointment.Resources.Add(resource);


                if (!string.IsNullOrEmpty(appointment.FluidType))
                {
                    switch (appointment.FluidType)
                    {
                        case FIFPConstants.FLUIDTYPE_OIL:
                            appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Oil", new SolidColorBrush(new Color() { R = 0xFF, G = 0x59, B = 0x59, A = 0xFF }));
                            break;
                        case FIFPConstants.FLUIDTYPE_COMBINED:
                            appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Combined", new SolidColorBrush(new Color() { R = 0x80, G = 0x0D, B = 0x54, A = 0xFF }));
                            break;
                        case FIFPConstants.FLUIDTYPE_WATER:
                            appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Water", new SolidColorBrush(new Color() { R = 0x4B, G = 0xAC, B = 0xC6, A = 0xFF }));
                            break;
                        case FIFPConstants.FLUIDTYPE_GAS:
                            appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Gas", new SolidColorBrush(new Color() { R = 0x93, G = 0xA8, B = 0x2A, A = 0xFF }));
                            break;
                        case FIFPConstants.TOWERTYPE_MANIFOLD:
                            appointment.Category = (appointment.IsAppliedSimops) ? new Category("", new SolidColorBrush(new Color() { R = 0x3D, G = 0x3D, B = 0x3D, A = 0xFF })) : new Category("Manifold", new SolidColorBrush(new Color() { R = 0x2E, G = 0x2E, B = 0x2E, A = 0xFF }));
                            break;
                        default:
                            break;
                    }
                }
            }

            appointmentGroup.Appointments = new List<FIFPAppointment>(plans);
            unitType.Resources.AddRange(unitList);
            lstResources.Add(unitType);


            appointmentGroup.ResourceTypes = lstResources;
            appointmentGroup.UnitList = unitList;

            if (OnAppointmentDataCompleted != null)
                OnAppointmentDataCompleted(this, new CustomEventArgs<AppointmentGroup>(appointmentGroup));

        }
        #endregion

        #region Generate Linked Shutdown Plans
        private void GenerateLinkedShutdownPlans(List<FIFPAppointment> currentPlans)
        {
            //1.delete linked shutdown, store it into db, reload application. we have to set IsLinkedShutdown = false, for deleted lsd. - OK
            //2.for combined tower, if we applied selected string, then we have to set it the selected string for the corresponding actiity after get it from database.-OK
            //3.for normal linked shutdown deletion, we set IsLinkedShutdown = false after get it from database.- OK
            //4.for reduced capacity list, we will set it correctly after get it from database. - OK
            //5.for capacity percentage, we no need to do any spl settings bcoz it is dependent with appointment. - OK
            //6.for radial switch list, we will set it correctly after get it from database.
            //7.for apply lsd simops, apply crossing line, we will set it correctly if it already applied.- OK

            LinkedShutdownList = new List<FIFPAppointment>();
            if (currentPlans != null && currentPlans.Count > 0)
            {
                foreach (FIFPAppointment appointment in currentPlans)
                {
                    if (appointment.ActivityCode != FIFPConstants.ACTIVITY_CODE_TPC)//Right now,If we create TPC activity we are not generating LSD for that.
                    {
                        if (appointment.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || appointment.UnitName == FIFPConstants.TOWER_UT_22A || appointment.UnitName == FIFPConstants.TOWER_UT_12A || appointment.UnitName == FIFPConstants.TOWER_UT_40)
                        {
                            GetLSDPlans(UnitList.Where(s => s.UnitName == appointment.UnitName).ToList<Unit>(), appointment, true);
                            appointment.LsdPlans = LinkedShutdownList;
                        }
                        else if (appointment.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM || appointment.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL)
                        {
                            GetLSDPlans(UnitList.Where(s => s.UnitName == appointment.UnitName).ToList<Unit>(), appointment, true);
                            appointment.LsdPlans = LinkedShutdownList;

                            List<int> radialSwitchList = new List<int>();
                            foreach (RadialSwitch rs in radialSwitchListFromDB)
                            {
                                foreach (FIFPAppointment a in LinkedShutdownList)
                                {
                                    if (rs.UnitId == a.UnitID && rs.StartDate == a.Start && rs.EndDate == a.End)
                                    {
                                        radialSwitchList.Add(rs.UnitId);
                                    }
                                }
                            }

                            if (radialSwitchList != null && radialSwitchList.Count > 0)
                            {
                                List<FIFPAppointment> lsdRadialSwtich = (from item in appointment.LsdPlans
                                                                         where radialSwitchList.Any(s => s == item.UnitID)
                                                                         select item).ToList<FIFPAppointment>();
                                if (appointment.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM)
                                {
                                    lsdRadialSwtich.ForEach(s => { s.LsdReason = "Rerouted to ByPass"; s.ActivityCode = "LSD"; });
                                }
                                else
                                {
                                    lsdRadialSwtich.ForEach(s => { s.LsdReason = "Rerouted to USOSSP"; s.ActivityCode = "LSD"; });
                                    //Generate new linked shutdown
                                }
                            }
                            if (appointment.LSDDeletedIds != null && appointment.LSDDeletedIds.Length > 0)
                            {
                                List<int> deletedByPassRadial = appointment.LSDDeletedIds.Split(',').Select(int.Parse).ToList();
                                List<int> deletedIds = deletedByPassRadial.Except(radialSwitchList).ToList<int>();
                                if (deletedIds.Count > 0)
                                {
                                    appointment.LsdPlans.Where(s => deletedIds.Any(p => p == s.UnitID)).ToList<FIFPAppointment>().ForEach(s => { s.LsdReason = "LSD deleted"; s.ActivityCode = "LSD"; });
                                }
                            }
                            //appointment.LSDDeletedIds = string.Join(",", bypassList);
                            //appointment.LsdPlans = appointment.LsdPlans.Except((from item in appointment.LsdPlans
                            //                                                    where bypassList.Any(s => s == item.UnitID)
                            //                                                    select item)).ToList<FIFPAppointment>();

                        }
                        else
                        {
                            GetLSDPlans(UnitList.Where(p => p.UnitID == appointment.UnitID).ToList(), appointment, true);
                            if (appointment.UnitType == FIFPConstants.UNITTYPE_WELL && (appointment.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || appointment.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL))
                            {
                                appointment.LsdPlans = new List<FIFPAppointment>();
                                Unit defaultSDUnit = UnitList.Where(p => p.UnitID == appointment.UnitID).FirstOrDefault();
                                if (defaultSDUnit != null)
                                {
                                    Unit parentUnit = UnitList.Where(p => p.UnitID == defaultSDUnit.ParentUnitID).FirstOrDefault();
                                    if (parentUnit != null)
                                    {
                                        appointment.LsdPlans.Add(new FIFPAppointment() { Division = appointment.Division, UnitStatus = appointment.UnitStatus, UnitID = parentUnit.UnitID, UnitName = parentUnit.UnitName, UnitType = parentUnit.UnitType, Start = appointment.Start, End = appointment.End, FluidType = appointment.FluidType, IsAppointmentDelete = true, IsLinkedShutdownPlan = true });
                                    }
                                }
                                appointment.LsdPlans.AddRange(LinkedShutdownList.Where(s => s.UnitName != appointment.UnitName).ToList<FIFPAppointment>());
                            }
                            else
                            {
                                if (appointment.IsAppliedLSDSimops)
                                {
                                    appointment.UnitStatus = "Open";
                                    appointment.IsDefaultUnitShutdown = false;
                                }
                                if (appointment.IsAppliedCrossingLine)
                                    appointment.IsDefaultUnitShutdown = false;

                                appointment.LsdPlans = LinkedShutdownList;
                            }
                        }

                        if (!string.IsNullOrEmpty(appointment.LSDDeletedIds))//After load it from database and also it's not applicable for USOSSP and ByPass
                        {
                            appointment.IsDefaultUnitShutdown = false;

                            if (appointment.IsAppliedLSDSimops || appointment.IsAppliedCrossingLine)
                            {
                                if (appointment.IsAppliedLSDSimops)
                                {
                                    List<int> wellRigUnitIds = appointment.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL && (s.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || s.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL)).Select(s => s.UnitID).Distinct().ToList<int>();//Open Pipeline and Well activities
                                    List<int> allUnitIds = appointment.LsdPlans.Select(s => s.UnitID).Distinct().ToList<int>();
                                    List<int> lsdUnitIds = new List<int>(allUnitIds.Except(wellRigUnitIds));
                                    appointment.LsdPlans.Where(w => lsdUnitIds.Any(s => s.Equals(w.UnitID))).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = false; });
                                }
                                if (appointment.IsAppliedCrossingLine)
                                {
                                    List<int> towerChildUnits = GetTowerChildUnitsExceptPipeline(appointment.UnitID);//get well and string units except pipeline because we have to open pipeline from default unit shutdown when we apply crossing line
                                    List<int> allUnitIds = appointment.LsdPlans.Select(s => s.UnitID).Distinct().ToList<int>();//select overall units
                                    List<int> lsdUnitIds = new List<int>(allUnitIds.Except(towerChildUnits));//
                                    appointment.LsdPlans.Where(w => lsdUnitIds.Any(s => s.Equals(w.UnitID))).ToList<FIFPAppointment>().ForEach(p => { p.IsLinkedShutdownPlan = false; });
                                }
                                appointment.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_STRING).ToList<FIFPAppointment>().ForEach(p => { p.CapacityPercentage = Math.Round(p.CapacityPercentage / 100, 2); });
                            }
                            else if (!string.IsNullOrEmpty(appointment.LSDDeletedIds))
                            {
                                List<int> deletedUnitIds = new List<int>();
                                if (!string.IsNullOrEmpty(appointment.LSDDeletedIds) && appointment.LSDDeletedIds.Length > 0)
                                {
                                    deletedUnitIds = appointment.LSDDeletedIds.Trim().Split(',').Select(int.Parse).ToList();
                                }

                                List<FIFPAppointment> lsdDeletedUnits = (from item in appointment.LsdPlans
                                                                         where deletedUnitIds.Any(s => s == item.UnitID)
                                                                         select item).ToList<FIFPAppointment>();

                                if (appointment.UnitName == FIFPConstants.PLATFORM_CP1_UNIT)
                                {
                                    foreach (FIFPAppointment deletedAppointment in lsdDeletedUnits)
                                    {
                                        if (deletedAppointment.UnitType == FIFPConstants.UNITTYPE_TOWER)
                                            deletedAppointment.LsdReason = "Switched to Auto injection";
                                        else
                                            deletedAppointment.LsdReason = "LSD deleted";
                                        deletedAppointment.ActivityCode = "LSD";
                                    }
                                }
                                else if (appointment.UnitName != FIFPConstants.UNITTYPE_USSC_PLATFORM && appointment.UnitName != FIFPConstants.UNITTYPE_BYPASS_MOL)
                                    lsdDeletedUnits.ForEach(s => { s.LsdReason = "LSD deleted"; s.ActivityCode = "LSD"; });
                                //Make All deleted unit id's linked shutdown = false.
                                MakeDeletedUnitsLSD(appointment);
                            }
                        }
                        else
                            appointment.IsDefaultUnitShutdown = true;
                        LinkedShutdownList = new List<FIFPAppointment>();
                    }
                }
            }

            if (radialSwitchListFromDB != null && radialSwitchListFromDB.Count > 0)
            {
                foreach (FIFPAppointment radialSwitchAppointment in currentPlans.Where(s => s.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM || s.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL))
                {
                    //Generate the new linked shutdown if the switching radial exists in Bypass or USOSSP
                    SwitchRadialForOverlappedActivities(currentPlans, radialSwitchAppointment, radialSwitchListFromDB);
                }
            }
        }

        private List<int> GetTowerChildUnitsExceptPipeline(int unitId)
        {
            List<Unit> lstChildUnits = UnitList.Where(s => s.ParentUnitID == unitId && s.UnitType != FIFPConstants.UNITTYPE_PIPELINE).ToList<Unit>();
            lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
            return lstChildUnits.Select(s => s.UnitID).ToList<int>();
        }


        private void GenerateLinkedShutdownPlansForNewActivity(FIFPAppointment appointment)
        {
            LinkedShutdownList = new List<FIFPAppointment>();
            if (appointment.ActivityCode != FIFPConstants.ACTIVITY_CODE_TPC)//Right now,If we create TPC activity we are not generating LSD for that.
            {
                if (appointment.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || appointment.UnitName == FIFPConstants.TOWER_UT_22A || appointment.UnitName == FIFPConstants.TOWER_UT_12A || appointment.UnitName == FIFPConstants.TOWER_UT_40)
                {
                    GetLSDPlans(UnitList.Where(s => s.UnitName == appointment.UnitName).ToList<Unit>(), appointment, true);
                    appointment.LsdPlans = LinkedShutdownList;
                    List<FIFPAppointment> towerplans = LinkedShutdownList.Where(s => s.UnitType == FIFPConstants.UNITTYPE_TOWER).ToList<FIFPAppointment>();
                }
                else if (appointment.UnitName == FIFPConstants.UNITTYPE_USSC_PLATFORM || appointment.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL)
                {
                    GetLSDPlans(UnitList.Where(s => s.UnitName == appointment.UnitName).ToList<Unit>(), appointment, true);
                    appointment.LsdPlans = LinkedShutdownList;
                }
                else
                {
                    GetLSDPlans(UnitList.Where(p => p.UnitID == appointment.UnitID).ToList(), appointment, true);
                    if (appointment.UnitType == FIFPConstants.UNITTYPE_WELL && (appointment.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || appointment.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL))
                    {
                        appointment.LsdPlans = new List<FIFPAppointment>();
                        Unit defaultSDUnit = UnitList.Where(p => p.UnitID == appointment.UnitID).FirstOrDefault();
                        if (defaultSDUnit != null)
                        {
                            Unit parentUnit = UnitList.Where(p => p.UnitID == defaultSDUnit.ParentUnitID).FirstOrDefault();
                            if (parentUnit != null)
                            {
                                appointment.LsdPlans.Add(new FIFPAppointment() { Division = appointment.Division, UnitStatus = appointment.UnitStatus, UnitID = parentUnit.UnitID, UnitName = parentUnit.UnitName, UnitType = parentUnit.UnitType, Start = appointment.Start, End = appointment.End, FluidType = appointment.FluidType, IsAppointmentDelete = true, IsLinkedShutdownPlan = true });
                            }
                        }
                        appointment.LsdPlans.AddRange(LinkedShutdownList.Where(s => s.UnitName != appointment.UnitName).ToList<FIFPAppointment>());
                    }
                    else
                        appointment.LsdPlans = LinkedShutdownList;
                }
            }
        }
        private void MakeDeletedUnitsLSD(FIFPAppointment appointment)
        {
            List<int> lstIds = new List<int>();
            try
            {
                if (!string.IsNullOrEmpty(appointment.LSDDeletedIds) && appointment.LSDDeletedIds.Length > 0)
                    lstIds = appointment.LSDDeletedIds.Split(',').Select(int.Parse).ToList();
                if (lstIds != null && lstIds.Count > 0)
                {
                    foreach (int unitId in lstIds)
                    {
                        ChildUnitList.Add(unitId);
                        Unit actualUnit = UnitList.Where(s => s.UnitID == unitId).FirstOrDefault();

                        if (actualUnit != null && actualUnit.UnitType == FIFPConstants.UNITTYPE_TOWER)
                        {
                            GetTowerChildUnits(unitId);
                        }
                        else
                        {
                            GetChildUnitNameList(UnitList.Where(s => s.ParentUnitID == unitId).ToList<Unit>());
                        }


                        //GetChildUnitNameList(UnitList.Where(s => s.ParentUnitID == unitId).ToList<Unit>());
                        ChildUnitList = ChildUnitList.Distinct().ToList<int>();//This child includes the the selected activity wells and strings and also the linked shutdown units
                        appointment.LsdPlans.Where(p => ChildUnitList.Any(q => q.Equals(p.UnitID))).ToList<FIFPAppointment>().ForEach(s => { s.IsLinkedShutdownPlan = false; });//This LsdPlans includes the the selected activity wells and strings and also the linked shutdown units
                        ChildUnitList = new List<int>();
                    }
                }
            }
            catch (Exception ex)
            { }
        }

        private void SwitchRadialForOverlappedActivities(List<FIFPAppointment> currentPlans, FIFPAppointment appointment, List<RadialSwitch> radialSwitchList)
        {
            List<FIFPAppointment> Plans = new List<FIFPAppointment>();
            int unitId;
            if (appointment.UnitType == FIFPConstants.UNITTYPE_PLATFORM)//OCCP
            {
                unitId = RadialSwitchDefaultValue.ByPassUnitId;
                Plans = currentPlans.Where(s => s.UnitID == RadialSwitchDefaultValue.ByPassUnitId).ToList<FIFPAppointment>();
            }
            else
            {
                unitId = RadialSwitchDefaultValue.OCCPUnitId;
                Plans = currentPlans.Where(s => s.UnitID == RadialSwitchDefaultValue.USOSSPUnitId).ToList<FIFPAppointment>();
            }
            if (radialSwitchList.Where(s => s.ParentUnitId == unitId).Count() > 0)
            {
                foreach (FIFPAppointment plan in Plans)
                {
                    //if (plan.LsdPlans != null && plan.LsdPlans.Count > 0)
                    //{
                    foreach (RadialSwitch rsAppointment in radialSwitchList)
                    {

                        bool overlap = !(plan.End < rsAppointment.StartDate || plan.Start > rsAppointment.EndDate);
                        if (overlap)
                        {
                            DateTime startDate = new DateTime();
                            DateTime endDate = new DateTime();
                            if (plan.Start > rsAppointment.StartDate)
                                startDate = plan.Start;
                            else
                                startDate = rsAppointment.StartDate;

                            if (plan.End < rsAppointment.EndDate)
                                endDate = plan.End;
                            else
                                endDate = rsAppointment.EndDate;

                            if (appointment.UnitType == FIFPConstants.UNITTYPE_PLATFORM)//OCCP
                            {
                                if (ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Contains(rsAppointment.UnitId))
                                    ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Remove(rsAppointment.UnitId);
                            }
                            else
                            {
                                ServiceLocator.Get<ShutdownMngVM>().OccpRadialUnitIds.Add(rsAppointment.UnitId);
                            }
                            Unit radialUnit = UnitList.Where(s => s.UnitID == rsAppointment.UnitId).FirstOrDefault();
                            FIFPAppointment lsdAppointment = new FIFPAppointment() { UnitID = rsAppointment.UnitId, UnitName = radialUnit.UnitName, UnitType = radialUnit.UnitType, Start = startDate, End = endDate, FluidType = radialUnit.FluidType, IsAppointmentDelete = true, IsLinkedShutdownPlan = true, UnitStatus = "C", Division = plan.Division, ParentActivityCode = plan.ActivityCode, IsRadialSwitch = true };
                            plan.LsdPlans.Add(lsdAppointment);
                            GetRadialSwitchLSDPlans(UnitList.Where(p => p.UnitID == rsAppointment.UnitId).SelectMany(s => s.ChildUnitList).ToList<Unit>(), lsdAppointment, plan);
                        }
                    }
                    //}
                }
            }
        }

        #region Generate Linked shutdowns
        private void GetRadialSwitchLSDPlans(List<Unit> lstUnits, FIFPAppointment appointment, FIFPAppointment plan)
        {
            foreach (Unit unit in lstUnits)
            {
                plan.LsdPlans.Add(new FIFPAppointment() { UnitID = unit.UnitID, UnitName = unit.UnitName, UnitType = unit.UnitType, Start = appointment.Start, End = appointment.End, OriginalStart = appointment.OriginalStart, OriginalEnd = appointment.OriginalEnd, FluidType = appointment.FluidType, IsAppointmentDelete = true, IsLinkedShutdownPlan = true, UnitStatus = "C", Division = appointment.Division, ParentActivityCode = plan.ActivityCode, IsRadialSwitch = true });
                this.GetRadialSwitchLSDPlans(UnitList.Where(p => p.ParentUnitID == unit.UnitID).ToList<Unit>(), appointment, plan);
            }
        }
        #endregion

        #region GetChildUnits

        private void GetTowerChildUnits(int unitId)
        {
            Unit towerUnit = UnitList.Where(p => p.UnitID == unitId).FirstOrDefault();
            if (towerUnit != null)
            {
                Unit pipelineUnit = UnitList.Where(p => p.UnitID == towerUnit.ParentUnitID).FirstOrDefault();
                ChildUnitList.Add(pipelineUnit.UnitID);
                List<Unit> lstChildUnits = UnitList.Where(s => s.ParentUnitID == unitId).ToList<Unit>();
                lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
                ChildUnitList.AddRange(lstChildUnits.Select(s => s.UnitID).ToList<int>());
            }
        }


        private void GetChildUnitNameList(List<Unit> lstUnits)
        {
            foreach (Unit unit in lstUnits)
            {
                ChildUnitList.Add(unit.UnitID);
                GetChildUnitNameList(UnitList.Where(p => p.ParentUnitID == unit.UnitID).ToList());
            }
        }

        #endregion

        private List<int> BuildDeletedLSD(List<FIFPAppointment> lsdPlans, string Ids)
        {
            List<int> lstIds = new List<int>();
            try
            {
                lstIds = Ids.Split(',').Select(int.Parse).ToList();
                List<Unit> lstChildUnits = UnitList.Where(s => lstIds.Any(p => p.Equals(s.ParentUnitID))).ToList<Unit>();
                lstChildUnits.AddRange(lstChildUnits.Where(s => s.UnitType == FIFPConstants.UNITTYPE_WELL).SelectMany(p => p.ChildUnitList).ToList<Unit>());
                lstIds.AddRange(lstChildUnits.Select(s => s.UnitID).ToList<int>());
                return lstIds;
            }
            catch (Exception ex)
            { }
            finally
            {

            }
            return lstIds;
        }

        private void GetLSDPlans(List<Unit> lstUnits, FIFPAppointment appointment, bool bInitial)
        {
            if (bInitial)
            {
                bInitial = false;
                if (appointment.UnitType == FIFPConstants.UNITTYPE_WELL && (appointment.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RIG || appointment.ActivityCode == FIFPConstants.ACTIVITY_TYPE_RGL))
                {
                    if (lstUnits != null && lstUnits.Count > 0)
                    {
                        Unit defaultSDUnit = UnitList.Where(p => p.UnitID == lstUnits[0].ParentUnitID).FirstOrDefault();
                        if (defaultSDUnit != null && defaultSDUnit.FluidType == FIFPConstants.FLUIDTYPE_COMBINED || defaultSDUnit.UnitName == FIFPConstants.TOWER_UT_22A || defaultSDUnit.UnitName == FIFPConstants.TOWER_UT_12A || defaultSDUnit.UnitName == FIFPConstants.TOWER_UT_40)
                        {
                            this.GetLSDPlans(UnitList.Where(s => s.UnitName == defaultSDUnit.UnitName).SelectMany(p => p.ChildUnitList).ToList(), appointment, bInitial);
                        }
                        else
                            this.GetLSDPlans(UnitList.Where(p => p.ParentUnitID == defaultSDUnit.UnitID).ToList(), appointment, bInitial);
                    }
                }
            }
            else
            {
                if (lstUnits != null && lstUnits.Count > 0)
                {
                    foreach (Unit unit in lstUnits)
                    {
                        FIFPAppointment fifpAppointment = new FIFPAppointment() { UnitID = unit.UnitID, UnitName = unit.UnitName, UnitType = unit.UnitType, Start = appointment.Start, End = appointment.End, OriginalStart = appointment.OriginalStart, OriginalEnd = appointment.OriginalEnd, FluidType = unit.FluidType, IsAppointmentDelete = true, IsLinkedShutdownPlan = true, UnitStatus = appointment.UnitStatus, Division = appointment.Division };
                        if (appointment != null && LinkedShutdownList.Where(s => s.UnitName == fifpAppointment.UnitName && s.Start == fifpAppointment.Start && s.End == fifpAppointment.End).Count() == 0)
                            LinkedShutdownList.Add(fifpAppointment);//Some duplicate linked shutdowns exists in OCCP. this is temporary fix
                    }
                }
            }

            foreach (Unit unit in lstUnits)
            {
                this.GetLSDPlans(UnitList.Where(p => p.ParentUnitID == unit.UnitID).ToList<Unit>(), appointment, bInitial);
            }
        }

        #endregion

        #region Create Linked Shutdown Plan
        private FIFPAppointment CreateLinkedShutdownPlan()
        {
            return new FIFPAppointment();
        }
        #endregion

        #region Menu Click Events
        private void ChangeSelectedButtonStyle(Button btnSave)
        {
            string tag = string.Empty;
            if (btnSave != null && btnSave.Tag != null)
                tag = Convert.ToString(btnSave.Tag);
            switch (tag)
            {
                case FIFPConstants.HYPERLINK_OPENRAWDATA:
                    OpenRawDataStyle = Application.Current.Resources[FIFPConstants.BUTTON_SELECTEDCOLOR] as Style;
                    OpenBaseScenarioStyle = ScenarioStyle = SaveAsStyle = SaveStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
                    break;
                case FIFPConstants.HYPERLINK_OPENBASE_SCENARIO:
                    OpenBaseScenarioStyle = Application.Current.Resources[FIFPConstants.BUTTON_SELECTEDCOLOR] as Style;
                    OpenRawDataStyle = ScenarioStyle = SaveAsStyle = SaveStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
                    break;
                case FIFPConstants.HYPERLINK_OPENSCENARIO:
                    ScenarioStyle = Application.Current.Resources[FIFPConstants.BUTTON_SELECTEDCOLOR] as Style;
                    OpenRawDataStyle = OpenBaseScenarioStyle = SaveAsStyle = SaveStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
                    break;
                case FIFPConstants.HYPERLINK_SAVE:
                    SaveStyle = Application.Current.Resources[FIFPConstants.BUTTON_SELECTEDCOLOR] as Style;
                    OpenRawDataStyle = OpenBaseScenarioStyle = ScenarioStyle = SaveAsStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
                    break;
                case FIFPConstants.HYPERLINK_SAVEAS:
                    SaveAsStyle = Application.Current.Resources[FIFPConstants.BUTTON_SELECTEDCOLOR] as Style;
                    OpenRawDataStyle = OpenBaseScenarioStyle = ScenarioStyle = SaveStyle = Application.Current.Resources[FIFPConstants.BUTTON_DEFAULTCOLOR] as Style;
                    break;
            }
        }
        #endregion

        #region SaveAs Button Logic
        private void SaveAsScenario(string scenarioName, string scenarioType, string userState)
        {

            BReloadScenario = true; //If we save as new scenario then we should show this in user's scenario list in Scenario Page.
            /*Activities are added or modified and also deleted*/
            ServiceLocator.Get<MainPageVM>().IsLoading = true;
            ServiceLocator.Get<MainPageVM>().LoadingMessage = FIFPConstants.LOADING_SAVEAS_MESSAGE;
            //Save and already exists Base scenario logic  
            string strActivities = null;
            List<FIFPAppointment> lstModifiedActivities = ImportPlans.Where(s => s.IsModified == 0 || s.IsModified == 1).ToList<FIFPAppointment>();
            if (lstModifiedActivities != null && lstModifiedActivities.Count > 0)
            {
                foreach (FIFPAppointment appointment in lstModifiedActivities)
                {
                    if (!string.IsNullOrEmpty(appointment.LSDDeletedIds))
                        appointment.LSDDeletedIds = appointment.LSDDeletedIds.Trim(',');

                    double capacityPercentage = appointment.CapacityPercentage;
                    if (appointment.IsAppliedLSDSimops || appointment.IsAppliedCrossingLine)
                    {
                        List<FIFPAppointment> stringActivities = appointment.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_STRING).ToList<FIFPAppointment>();
                        if (stringActivities != null && stringActivities.Count > 0)
                            capacityPercentage = stringActivities[0].CapacityPercentage;
                    }

                    if (appointment.IsModified == 0)//16
                        strActivities += appointment.IsModified.ToString() + "|" + appointment.PlanID + "|" + appointment.Start.ToString("dd/MM/yyyy") + "|" + appointment.End.ToString("dd/MM/yyyy") + "|" + capacityPercentage + "|" + appointment.ReducedCapacity + "|" + appointment.LSDDeletedIds + "|" + appointment.SelectedOilString + "|" + appointment.IsAppliedSimops + "|" + appointment.IsAppliedLSDSimops + "|" + appointment.IsAppliedCrossingLine + "|" + appointment.IsBypassMOL + "|" + appointment.ActivityId + "|" + appointment.DB_OverlapId + "|" + appointment.IsRDVisibility + "|" + appointment.Remarks + "|" + appointment.IsOverlapRemoved + "|";
                    else if (appointment.IsModified == 1)//18
                        strActivities += appointment.IsModified.ToString() + "|" + appointment.UnitID + "|" + appointment.ActivityId + "|" + appointment.DivisionId + "|" + appointment.Start.ToString("dd/MM/yyyy") + "|" + appointment.End.ToString("dd/MM/yyyy") + "|" + appointment.Remarks + "|" + appointment.PlanActivityId + "|" + appointment.LSDDeletedIds + "|" + appointment.SelectedOilString + "|" + capacityPercentage + "|" + appointment.ReducedCapacity + "|" + appointment.IsAppliedSimops + "|" + appointment.IsAppliedLSDSimops + "|" + appointment.IsAppliedCrossingLine + "|" + appointment.IsBypassMOL + "|" + appointment.DB_OverlapId + "|" + appointment.IsRDVisibility + "|" + appointment.IsOverlapRemoved + "|";
                }
            }


            if (DeletedActivityIds != null && DeletedActivityIds.Count > 0)//If activities are deleted,then we have to update that into database
            {
                foreach (int planId in DeletedActivityIds)
                    strActivities += "2|" + planId + "|";
            }
            if (!string.IsNullOrEmpty(strActivities))
                strActivities = strActivities.TrimEnd('|');

            string[] param = new string[] { scenarioName.Trim(), scenarioType, string.Empty, App.LoginUserName, Convert.ToString(CurrentScenarioId), strActivities };
            RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
            queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SAVEAS_NEWSCENARIO_QUERY_ID, param, userState);
            queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForSaveBaseScenario_DataCompleted);
        }

        void ImportVM_QueryForSaveBaseScenario_DataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            ServiceLocator.Get<MainPageVM>().IsLoading = false;
            ServiceLocator.Get<MainPageVM>().IsSaveButtonEnabled = true;
            ServiceLocator.Get<MainPageVM>().IsCalculateButtonEnabled = true;
            if (e.Result != null && e.Error == null)
            {
                if (e.UserState.ToString() == "SaveAsBaseScenario" || e.UserState.ToString() == "SaveAsNewScenario" || e.UserState.ToString() == "SaveCurrentScenario")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            List<Scenario> retScenarioList = (from item in doc.Descendants("Query")
                                                              select new Scenario
                                                              {
                                                                  ScenarioId = item.Element("scenarioId") != null ? Convert.ToInt32(item.Element("scenarioId").Value) : 0,
                                                                  ScenarioName = item.Element("scenarioName") != null ? Convert.ToString(item.Element("scenarioName").Value) : string.Empty,
                                                                  ScenarioDescription = item.Element("scenarioName") != null ? Convert.ToString(item.Element("scenarioName").Value) : string.Empty,
                                                                  NewPlanId = item.Element("realNewPlanId") != null ? Convert.ToInt32(item.Element("realNewPlanId").Value) : 0,
                                                                  ActivityId = item.Element("tempNewPlanId") != null ? Convert.ToInt32(item.Element("tempNewPlanId").Value) : 0,
                                                              }).ToList<Scenario>();
                            if (retScenarioList != null && retScenarioList.Count > 0)
                            {
                                Scenario SelectedScenario = retScenarioList[0];


                                if (e.UserState.ToString() == "SaveAsBaseScenario")//SaveAs Base Scenario
                                {
                                    if (SelectedScenario != null && string.IsNullOrEmpty(SelectedScenario.ScenarioName))
                                        ShowPopup(FIFPConstants.WARNINGTITLE_INTEGRATION_ALREADY, FIFPConstants.WARNINGMESSAGE_INTEGRATION_ALREADY);
                                    else
                                    {
                                        //If the user applied reduced capacity for any units on LSD page
                                        if (ServiceLocator.Get<ShutdownMngVM>().IsRCReversed || (ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList != null && ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList.Count > 0))
                                        {
                                            ServiceLocator.Get<ShutdownMngVM>().IsRCReversed = false;
                                            IsRCorRadialRequest = false;
                                            SaveReducedCapacity(GetCombinedRCList(), SelectedScenario.ScenarioId);
                                        }
                                        if (ServiceLocator.Get<AppointmentVM>().RadialSwitchList != null && ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Count > 0)
                                        {
                                            IsRCorRadialRequest = false;
                                            SaveRadialSwitch(ServiceLocator.Get<AppointmentVM>().RadialSwitchList, SelectedScenario.ScenarioId);
                                        }
                                        //Get the save scenario from database and load it into context menu
                                        GetScenariosFromDB();
                                        ShowPopup(FIFPConstants.WARNINGTITLE_SAVEAS_INTEGRATION_SCENARIO, FIFPConstants.WARNINGMESSAGE_SAVEAS_INTEGRATION_SCENARIO);
                                    }
                                }
                                else if (e.UserState.ToString() == "SaveAsNewScenario")//SaveAs New Scenario
                                {
                                    if (SelectedScenario != null && string.IsNullOrEmpty(SelectedScenario.ScenarioName))
                                        ShowPopup(FIFPConstants.DISPLAY_SCENARIO, string.Format(FIFPConstants.SCENARIO_ALREADY_EXISTS, SelectedScenario.ScenarioName));
                                    else
                                    {
                                        //If the user applied reduced capacity for any units on LSD page
                                        if (ServiceLocator.Get<ShutdownMngVM>().IsRCReversed || (ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList != null && ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList.Count > 0))
                                        {
                                            ServiceLocator.Get<ShutdownMngVM>().IsRCReversed = false;
                                            IsRCorRadialRequest = false;
                                            SaveReducedCapacity(GetCombinedRCList(), SelectedScenario.ScenarioId);
                                        }
                                        if (ServiceLocator.Get<AppointmentVM>().RadialSwitchList != null && ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Count > 0)
                                        {
                                            IsRCorRadialRequest = false;
                                            SaveRadialSwitch(ServiceLocator.Get<AppointmentVM>().RadialSwitchList, SelectedScenario.ScenarioId);
                                        }
                                        //Get the save scenario from database and load it into context menu
                                        GetScenariosFromDB();
                                        ShowPopup(FIFPConstants.WARNINGTITLE_SAVEAS_SCENARIO, FIFPConstants.WARNINGMESSAGE_SAVENEW_SCENARIO);
                                    }
                                    _validationResults.Clear();
                                    ScenarioName = string.Empty;
                                    scenarioPopup.Close();
                                }
                                else if (e.UserState.ToString() == "SaveCurrentScenario") //Save Scenario
                                {
                                    if (ServiceLocator.Get<ShutdownMngVM>().IsRCReversed || (ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList != null && ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList.Count > 0))
                                    {
                                        ServiceLocator.Get<ShutdownMngVM>().IsRCReversed = false;
                                        IsRCorRadialRequest = false;
                                        SaveReducedCapacity(ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList, CurrentScenarioId);
                                    }
                                    if (ServiceLocator.Get<AppointmentVM>().RadialSwitchList != null && ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Count > 0)
                                    {
                                        IsRCorRadialRequest = false;
                                        SaveRadialSwitch(ServiceLocator.Get<AppointmentVM>().RadialSwitchList, SelectedScenario.ScenarioId);
                                    }
                                    foreach (FIFPAppointment appointment in ImportPlans.Where(s => s.IsModified == 1))
                                    {
                                        foreach (Scenario scenario in retScenarioList)
                                        {
                                            if (scenario.ActivityId.Equals(appointment.PlanActivityId))
                                            {
                                                appointment.IsModified = -1; appointment.PlanActivityId = 0;
                                                appointment.PlanID = scenario.NewPlanId;
                                            }
                                        }
                                    }
                                    foreach (FIFPAppointment appointment in ImportPlans.Where(s => s.IsModified == 0))
                                    {
                                        appointment.IsModified = -1;
                                    }
                                    if (DeletedActivityIds.Count > 0)
                                    {
                                        BindData();//We should update gantt chart if it has any deleted activities
                                        DeletedActivityIds.Clear();
                                    }
                                    ShowPopup(FIFPConstants.WARNINGTITLE_SAVE_SCENARIO, FIFPConstants.WARNINGMESSAGE_SAVE_SCENARIO);
                                }
                            }
                            else
                            {
                                ScenarioName = string.Empty;
                                if (scenarioPopup != null)
                                    scenarioPopup.Close();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ServiceLocator.Get<MainPageVM>().IsLoading = false;
                        ServiceLocator.Get<MainPageVM>().IsSaveButtonEnabled = true;
                        ServiceLocator.Get<MainPageVM>().IsCalculateButtonEnabled = true;
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                MessageBox.Show("Database connection error when saveas scenario.");
            }
        }

        void scenarioPopup_Closed(object sender, EventArgs e)
        {
        }

        private List<RadialSwitch> MergeRadialSwitchDBWithTempList()
        {
            List<RadialSwitch> tempList = new List<RadialSwitch>();
            if (RadialSwitchListFromDB != null && RadialSwitchListFromDB.Count > 0)
                tempList.AddRange(RadialSwitchListFromDB);
            if (ServiceLocator.Get<AppointmentVM>().RadialSwitchList != null && ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Count > 0)
                tempList.AddRange(ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Where(s => s.IsRevert == false));
            return tempList;
        }

        private void SaveRadialSwitch(List<RadialSwitch> radialSwitchList, int currentScenarioId)
        {
            string strActivities = null;
            foreach (RadialSwitch rswitch in radialSwitchList)
            {
                strActivities += rswitch.UnitId + "|" + rswitch.ParentUnitId + "|" + rswitch.StartDate.ToString("dd/MM/yyyy") + "|" + rswitch.EndDate.ToString("dd/MM/yyyy") + "|";
            }
            if (!string.IsNullOrEmpty(strActivities))
            {
                string[] param = new string[] { Convert.ToString(currentScenarioId), strActivities };
                RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
                queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SELECT_SaveSwitchedRadials_QUERY_ID, param, "RadialSwitch");
                queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForRadialSwitch_DataCompleted);
            }
        }

        private void SaveReducedCapacity(List<ReducedCapacity> capacityList, int currentScenarioId)
        {
            string strActivities = null;
            foreach (ReducedCapacity capacity in capacityList)
            {
                strActivities += capacity.UnitId + "|" + capacity.ParentUnitId + "|" + capacity.StartDate.ToString("dd/MM/yyyy") + "|" + capacity.EndDate.ToString("dd/MM/yyyy") + "|" + capacity.OriginalUnitCapacity + "|" + capacity.ReducedUnitCapacity + "|" + capacity.PlanId + "|";
            }
            //if (!string.IsNullOrEmpty(strActivities))
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = true;
                ServiceLocator.Get<MainPageVM>().LoadingMessage = FIFPConstants.LOADING_SAVERC_MESSAGE;
                string[] param = new string[] { Convert.ToString(currentScenarioId), strActivities };
                RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
                queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SAVE_SaveReducedCapacity_QUERY_ID, param, "ReducedCapacity");
                queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForReducedCapacity_DataCompleted);
            }
        }

        void ImportVM_QueryForRadialSwitch_DataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            ServiceLocator.Get<MainPageVM>().IsLoading = false;
            ServiceLocator.Get<MainPageVM>().IsSaveButtonEnabled = true;
            ServiceLocator.Get<MainPageVM>().IsCalculateButtonEnabled = true;
            if (e.Error == null && e.UserState.ToString() == "RadialSwitch")
            {

            }
        }

        void ImportVM_QueryForReducedCapacity_DataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            ServiceLocator.Get<MainPageVM>().IsLoading = false;
            ServiceLocator.Get<MainPageVM>().IsSaveButtonEnabled = true;
            ServiceLocator.Get<MainPageVM>().IsCalculateButtonEnabled = true;
            if (e.Error == null && e.UserState.ToString() == "ReducedCapacity")
            {
                if (IsRCorRadialRequest)
                {
                    ServiceLocator.Get<MainPageVM>().IsLoading = false;
                    IsRCorRadialRequest = false;
                }
            }
        }
        #endregion

        #region Save Button Logic
        public void SaveScenario()
        {
            //ChangeSelectedButtonStyle(btnSaveAs);
            string[] param = null;

            List<FIFPAppointment> lstModifiedActivities = ImportPlans.Where(s => s.IsModified == 0 || s.IsModified == 1).ToList<FIFPAppointment>();
            if ((lstModifiedActivities != null && lstModifiedActivities.Count > 0) || DeletedActivityIds.Count > 0)
            {
                string strActivities = string.Empty;
                foreach (FIFPAppointment appointment in lstModifiedActivities)
                {
                    //List<int> lsdIds = appointment.LsdPlans.Where(s => s.IsLinkedShutdownPlan == false).Select(p => p.UnitID).ToList<int>();
                    //string Ids = string.Join(",", lsdIds);
                    if (!string.IsNullOrEmpty(appointment.LSDDeletedIds))
                        appointment.LSDDeletedIds = appointment.LSDDeletedIds.Trim(',');

                    double capacityPercentage = appointment.CapacityPercentage;
                    if (appointment.IsAppliedLSDSimops || appointment.IsAppliedCrossingLine)
                    {
                        List<FIFPAppointment> stringActivities = appointment.LsdPlans.Where(s => s.UnitType == FIFPConstants.UNITTYPE_STRING).ToList<FIFPAppointment>();
                        if (stringActivities != null && stringActivities.Count > 0)
                            capacityPercentage = stringActivities[0].CapacityPercentage;
                    }

                    if (appointment.IsModified == 0)//16 parameters
                        strActivities += appointment.IsModified.ToString() + "|" + appointment.PlanID + "|" + appointment.Start.ToString("dd/MM/yyyy") + "|" + appointment.End.ToString("dd/MM/yyyy") + "|" + capacityPercentage + "|" + appointment.ReducedCapacity + "|" + appointment.LSDDeletedIds + "|" + appointment.SelectedOilString + "|" + appointment.IsAppliedSimops + "|" + appointment.IsAppliedLSDSimops + "|" + appointment.IsAppliedCrossingLine + "|" + appointment.IsBypassMOL + "|" + appointment.ActivityId + "|" + appointment.DB_OverlapId + "|" + appointment.IsRDVisibility + "|" + appointment.Remarks + "|" + appointment.IsOverlapRemoved + "|";
                    else if (appointment.IsModified == 1)//18 parameters
                        strActivities += appointment.IsModified.ToString() + "|" + appointment.UnitID + "|" + appointment.ActivityId + "|" + appointment.DivisionId + "|" + appointment.Start.ToString("dd/MM/yyyy") + "|" + appointment.End.ToString("dd/MM/yyyy") + "|" + appointment.Remarks + "|" + appointment.PlanActivityId + "|" + appointment.LSDDeletedIds + "|" + appointment.SelectedOilString + "|" + capacityPercentage + "|" + appointment.ReducedCapacity + "|" + appointment.IsAppliedSimops + "|" + appointment.IsAppliedLSDSimops + "|" + appointment.IsAppliedCrossingLine + "|" + appointment.IsBypassMOL + "|" + appointment.DB_OverlapId + "|" + appointment.IsRDVisibility + "|" + appointment.IsOverlapRemoved + "|";
                }
                if (DeletedActivityIds != null && DeletedActivityIds.Count > 0)
                {
                    foreach (int planId in DeletedActivityIds)
                        strActivities += "2|" + planId + "|";
                }
                if (!string.IsNullOrEmpty(strActivities))
                    //param = new string[] { strActivities.TrimEnd('|'), Convert.ToString(CurrentScenarioId) };
                    param = new string[] { strActivities, Convert.ToString(CurrentScenarioId) };
                else
                    param = new string[] { null, Convert.ToString(CurrentScenarioId) };
                ServiceLocator.Get<MainPageVM>().IsLoading = true;
                ServiceLocator.Get<MainPageVM>().LoadingMessage = FIFPConstants.LOADING_SAVE_MESSAGE;
                RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
                queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SAVE_CURRENTSCENARIO_QUERY_ID, param, "SaveCurrentScenario");
                queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForSaveBaseScenario_DataCompleted);

            }
            else if (ServiceLocator.Get<ShutdownMngVM>().IsRCReversed || (ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList != null && ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList.Count > 0) || (ServiceLocator.Get<AppointmentVM>().RadialSwitchList != null && ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Count > 0))
            {
                ServiceLocator.Get<ShutdownMngVM>().IsRCReversed = false;
                IsRCorRadialRequest = true;
                //if (ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList.Count > 0)
                SaveReducedCapacity(GetCombinedRCList(), CurrentScenarioId);
                if (ServiceLocator.Get<AppointmentVM>().RadialSwitchList.Count > 0)
                    SaveRadialSwitch(ServiceLocator.Get<AppointmentVM>().RadialSwitchList, CurrentScenarioId);
            }
            else
            {
                ShowPopup(FIFPConstants.WARNINGTITLE_SAVE_SCENARIO, FIFPConstants.WARNINGMESSAGE_SAVE_NOCHANGE);
                ServiceLocator.Get<MainPageVM>().IsSaveButtonEnabled = true;
                ServiceLocator.Get<MainPageVM>().IsCalculateButtonEnabled = true;
            }
        }

        public List<ReducedCapacity> GetCombinedRCList()
        {
            List<ReducedCapacity> lstCombinedRDList = new List<ReducedCapacity>();
            if (ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList != null && ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList.Count > 0)
            {
                foreach (ReducedCapacity dbCapacity in ReducedCapacityList)
                {
                    if (!ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList.Contains(dbCapacity))
                        lstCombinedRDList.Add(dbCapacity);
                }
                foreach (ReducedCapacity capacity in ServiceLocator.Get<ShutdownMngVM>().ReducedCapacityList)
                    lstCombinedRDList.Add(capacity);
            }
            else
                lstCombinedRDList = ReducedCapacityList;
            return lstCombinedRDList;
        }

        private void SaveMaxCapacityDataIntoDB(ReportData reportData)
        {
            if (reportData != null)
            {
                string[] param = null;
                string strActivities = string.Empty;
                foreach (EffectiveCapacityData capacityData in reportData.RCList)
                {
                    strActivities += capacityData.Date.ToString("dd/MM/yyyy") + "|" + Math.Round(capacityData.EffectiveCapacity, 2) + "|" + "RC" + "|";
                }
                foreach (EffectiveCapacityData capacityData in reportData.MCList)
                {
                    strActivities += capacityData.Date.ToString("dd/MM/yyyy") + "|" + Math.Round(capacityData.EffectiveCapacity, 2) + "|" + "MC" + "|";
                }
                if (!string.IsNullOrEmpty(strActivities))
                {
                    param = new string[] { "-1", "no user", "no user", strActivities.TrimEnd('|') };
                    RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
                    queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SAVE_CURRENTSCENARIO_CAPACITYDATA_QUERY_ID, param, "SaveCapacityData");
                    queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForSaveCapacity_DataCompleted);
                }
            }
        }
        private void SaveCapacityDataIntoDB(ReportData reportData)
        {
            if (reportData != null)
            {
                string[] param = null;
                string strActivities = string.Empty;
                foreach (EffectiveCapacityData capacityData in reportData.ECList)
                {
                    strActivities += capacityData.Date.ToString("dd/MM/yyyy") + "|" + Math.Round(capacityData.EffectiveCapacity, 2) + "|" + "EC" + "|";
                }
                foreach (EffectiveCapacityData capacityData in reportData.OilList)
                {
                    strActivities += capacityData.Date.ToString("dd/MM/yyyy") + "|" + Math.Round(capacityData.EffectiveCapacity, 2) + "|" + "OC" + "|";
                }
                if (!string.IsNullOrEmpty(strActivities))
                {
                    param = new string[] { Convert.ToString(CurrentScenarioId), CurrentScenario.ScenarioName, App.LoginUserName, strActivities.TrimEnd('|') };
                    RelationalDataServiceClient queryClient = new RelationalDataServiceClient(FIFPServiceHostUtil.GetQueryBasicHttpBinding(), FIFPServiceHostUtil.GetQueryEndpointAddress());
                    queryClient.QueryForDataAsync(FIFPConstants.DATASOURCE_ID, FIFPConstants.SAVE_CURRENTSCENARIO_CAPACITYDATA_QUERY_ID, param, "SaveCapacityData");
                    queryClient.QueryForDataCompleted += new EventHandler<QueryForDataCompletedEventArgs>(ImportVM_QueryForSaveCapacity_DataCompleted);
                }
            }
        }
        #endregion

        #region Show default plans
        private void ShowDefaultPlans(Button btnReset)
        {
            ImportPlans = ScenarioPlans;
            ServiceLocator.Get<FilterVM>().StartDate = (ImportPlans != null && ImportPlans.Count > 0) ? ImportPlans.Min(s => s.Start) : new DateTime(DateTime.Now.Year, 1, 1);
            ServiceLocator.Get<FilterVM>().EndDate = (ImportPlans != null && ImportPlans.Count > 0) ? ImportPlans.Max(s => s.End) : new DateTime(DateTime.Now.Year, 12, 31);
            if (ServiceLocator.Get<MainPageVM>().IsImportChecked)
                ServiceLocator.Get<FilterVM>().ResetFilterData();
            else
                ServiceLocator.Get<FilterVM>().ResetLsdFilterData();

            LoadTimelineView((from item in ImportPlans orderby item.nIndex ascending select item).ToList<FIFPAppointment>());
        }
        #endregion


        #region Undo logic
        private void UndoActivitiesByOneLevelBack(Button btnUndo)
        {
            UndoScheduleViewActivities();
        }

        public void UndoScheduleViewActivities()
        {
            if (ServiceLocator.Get<MainPageVM>().IsImportChecked)
            {
                if (ImportPlans != null && ImportPlans.Count > 0 && ImportPlans.Where(s => s.ActivityLevel > 1).Count() > 0)
                {
                    foreach (FIFPAppointment appointment in ImportPlans.Where(s => s.ActivityLevel > 1))
                    {
                        appointment.Start = appointment.ModifiedStart;
                        appointment.End = appointment.ModifiedEnd;
                    }
                    LoadTimelineView((from item in ImportPlans orderby item.nIndex ascending select item).ToList<FIFPAppointment>());
                }
            }
            else if (ServiceLocator.Get<MainPageVM>().IsOverLapChecked)
            {
                ServiceLocator.Get<OverlapVM_New>().UndoOverlapActivities();
            }
            else if (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsLinkedSDChecked)
            {
                ServiceLocator.Get<ShutdownMngVM>().UndoLSDActivities();
            }
            else if (ServiceLocator.Get<MainPageVM>().IsOptimizationChecked && ServiceLocator.Get<MainPageVM>().IsOptMngChecked)
            {
                ServiceLocator.Get<OptMngVM>().UndoOptimizationActivities();
            }
        }
        #endregion

        #region Calculate Max Button Logic
        private void CalculateMaxFieldCapacity(Button btnCalculateMax)
        {
            ServiceLocator.Get<MainPageVM>().IsLoading = true;
            ServiceLocator.Get<MainPageVM>().LoadingMessage = FIFPConstants.LOADING_CALCULATE_MESSAGE;
            ThreadPool.QueueUserWorkItem((threadState) =>
            {
                SetInputDataForCalculation();

                DateTime startDate = new DateTime(ServiceLocator.Get<FilterVM>().StartDate.Year, ServiceLocator.Get<FilterVM>().StartDate.Month, 1);
                DateTime endDate = new DateTime(ServiceLocator.Get<FilterVM>().EndDate.Year, ServiceLocator.Get<FilterVM>().EndDate.Month, DateTime.DaysInMonth(ServiceLocator.Get<FilterVM>().EndDate.Year, ServiceLocator.Get<FilterVM>().EndDate.Month));

                DateTime selectedStartDate = startDate;
                DateTime selectedEndDate = endDate;

                //DateTime selectedStartDate = ServiceLocator.Get<FilterVM>().StartDate;
                //DateTime selectedEndDate = ServiceLocator.Get<FilterVM>().EndDate;
                //DateTime calculateEndDate = new DateTime(selectedStartDate.Year, 12, 31);

                //DateTime startDayForRC = new DateTime(selectedStartDate.Year, 1, 1);
                List<EffectiveCapacityData> RCList = getRCData(selectedStartDate, selectedEndDate);

                //max field capacity
                //DateTime startDayForMC = new DateTime(selectedStartDate.Year, 1, 1);
                selectedStartDate = startDate;
                List<EffectiveCapacityData> MCList = getMCData(selectedStartDate, selectedEndDate);

                Dispatcher.BeginInvoke(() =>
                {
                    //We have to check whether the max capacity calculation data would be in database. If yes, we have to send along with this list.
                    ReportData reportData = new ReportData();
                    reportData.ScenarioName = CurrentScenarioName;
                    reportData.RCList = RCList;
                    reportData.MCList = MCList;
                    BReloadScenario = true;
                    SaveMaxCapacityDataIntoDB(reportData);
                    retXml = SerializeObject(reportData);
                    if (!IsMCBrowserOpened)
                    {
                        IsMCBrowserOpened = true;
                        string url = HtmlPage.Document.DocumentUri.AbsoluteUri;
                        url = url.Substring(0, url.IndexOf(HtmlPage.Document.DocumentUri.LocalPath));
                        string pageName = App.CustomPageName;
                        string queryString = "?navType=MC&mcSenderName=" + strMCSender + "&mcReceiverName=" + strMCReceiver;
                        Uri b = new Uri(String.Format("{0}{1}", url.ToString(), "/" + pageName + (pageName.Contains("?") ? "&" : "") + queryString));
                        HtmlPage.Window.Navigate(b, "_blank");
                    }
                    localMessageMCSender.SendAsync(retXml);
                    ServiceLocator.Get<MainPageVM>().IsLoading = false;
                });
            });
        }

        #endregion

        #region Calculate Button Logic


        public void Calculate(Button btnCalculate)
        {
            ServiceLocator.Get<MainPageVM>().IsLoading = true;
            ServiceLocator.Get<MainPageVM>().LoadingMessage = FIFPConstants.LOADING_CALCULATE_MESSAGE;
            ThreadPool.QueueUserWorkItem((threadState) =>
            {
                SetInputDataForCalculation();

                DateTime startDate = new DateTime(ServiceLocator.Get<FilterVM>().StartDate.Year, ServiceLocator.Get<FilterVM>().StartDate.Month, 1);
                DateTime endDate = new DateTime(ServiceLocator.Get<FilterVM>().EndDate.Year, ServiceLocator.Get<FilterVM>().EndDate.Month, DateTime.DaysInMonth(ServiceLocator.Get<FilterVM>().EndDate.Year, ServiceLocator.Get<FilterVM>().EndDate.Month));
                DateTime selectedStartDate = startDate;
                DateTime selectedEndDate = endDate;
                //DateTime calculateEndDate = new DateTime(selectedStartDate.Year, 12, 31);
                //if(selectedEndDate.Year - selectedStartDate.Year >=1)
                //    calculateEndDate = new DateTime(selectedStartDate.Year+1, 12, 31);    
                //else
                //    calculateEndDate = new DateTime(selectedEndDate.Year, 12, 31);
                //rc
                //DateTime startDayForRC = new DateTime(selectedStartDate.Year, 1, 1);
                List<EffectiveCapacityData> RCList = getRCData(selectedStartDate, selectedEndDate);

                //Total Oil Capacity
                selectedStartDate = startDate;
                List<EffectiveCapacityData> OilList = getOilData(selectedStartDate, selectedEndDate);
                //ec
                //DateTime startDayForEC = new DateTime(selectedStartDate.Year, 1, 1);
                selectedStartDate = startDate;
                List<EffectiveCapacityData> ECList = getECData(selectedStartDate, selectedEndDate);

                //Apply Monitoring and unplanned percentages
                if (ECList != null && ECList.Count > 0)
                {
                    foreach (EffectiveCapacityData ecData in ECList)
                    {
                        if (FieldData != null)
                            ecData.EffectiveCapacity = ecData.EffectiveCapacity - (ecData.EffectiveCapacity * (Math.Round(FieldData.CurrentMonitoringPercentage / 100, 4) + Math.Round(FieldData.CurrentUnplannedLossesPercentage / 100, 4)));
                    }
                }

                //loss
                //DateTime startDayForLoss = new DateTime(selectedStartDate.Year, 1, 1);
                selectedStartDate = startDate;
                List<LossByDivisionAndData> LOSSList = new List<LossByDivisionAndData>();//for loss chart
                List<LossByDivisionAndData> allMonthlyLossList = new List<LossByDivisionAndData>();//for monthly loss chart
                getLossData(selectedStartDate, selectedEndDate, LOSSList, allMonthlyLossList, RCList, ECList);
                //max field capacity
                //DateTime startDayForMC = new DateTime(selectedStartDate.Year, 1, 1);
                selectedStartDate = startDate;
                List<EffectiveCapacityData> MCList = getMCData(selectedStartDate, selectedEndDate);


                Dispatcher.BeginInvoke(() =>
                {
                    //We have to check whether the max capacity calculation data would be in database. If yes, we have to send along with this list.
                    ReportData reportData = new ReportData();
                    reportData.ScenarioName = CurrentScenarioName;
                    reportData.OilList = OilList;
                    reportData.RCList = RCList;
                    reportData.MCList = MCList;
                    reportData.ECList = ECList;
                    //reportData.DivisionLossList = LOSSList;
                    reportData.MonthlyLossList = allMonthlyLossList;
                    BReloadScenario = true;
                    SaveCapacityDataIntoDB(reportData);
                    retXml = SerializeObject(reportData);

                    if (!IsECBrowserOpened)
                    {
                        IsECBrowserOpened = true;
                        string url = HtmlPage.Document.DocumentUri.AbsoluteUri;
                        url = url.Substring(0, url.IndexOf(HtmlPage.Document.DocumentUri.LocalPath));
                        string pageName = App.CustomPageName;
                        string queryString = "?navType=EC&ecSenderName=" + strECSender + "&ecReceiverName=" + strECReceiver;
                        Uri b = new Uri(String.Format("{0}{1}", url.ToString(), "/" + pageName + (pageName.Contains("?") ? "&" : "") + queryString));
                        HtmlPage.Window.Navigate(b, "_blank");
                    }
                    localMessageECSender.SendAsync(retXml);
                });
            });
        }

        private void CalculateCapacityAndLoss(bool isMax)
        {

        }

        private void SetInputDataForCalculation()
        {
            /*
            //We have to add bypass radials linked shutdown to occp(if it has an activity) linked shutdown.
            if (ImportPlans != null && ImportPlans.Count > 0 && ImportPlans.Where(s => s.UnitName == FIFPConstants.PLATFORM_OCCP_UNIT).Count() > 0)
            {
                List<Unit> byPassRadialList = UnitList.Where(s => s.UnitName == FIFPConstants.UNITTYPE_BYPASS_MOL).SelectMany(p => p.ChildUnitList).ToList<Unit>();
                foreach (FIFPAppointment appointment in ImportPlans.Where(s => s.UnitName == FIFPConstants.PLATFORM_OCCP_UNIT))
                {
                    GetLSDPlans(byPassRadialList, appointment, true);
                    appointment.LsdPlans.AddRange(LinkedShutdownList);
                }
            }
            */

            List<FIFPAppointment> lsdList = new List<FIFPAppointment>();
            foreach (FIFPAppointment appointment in ImportPlans)
            {
                if (appointment.IsAppliedLSDSimops && appointment.UnitStatus == "Open")
                { }
                else
                    lsdList.Add(appointment);
                /* throws invalid cross thread access exception
                foreach (FIFPAppointment activity in appointment.LsdPlans)
                {
                    activity.Start = appointment.Start; activity.End = appointment.End;
                }*/
                lsdList.AddRange(appointment.LsdPlans.Where(s => s.IsLinkedShutdownPlan == true || s.IsAppliedLSDSimops == true || s.IsAppliedCrossingLine == true).ToList<FIFPAppointment>());
            }

            /*
            foreach (FIFPAppointment f in lsdList)
            {
                DateTime ftStart = new DateTime(f.Start.Year, f.Start.Month, f.Start.Day);
                DateTime ftEnd = new DateTime(f.End.Year, f.End.Month, f.End.Day);
                f.Start = ftStart;
                f.End = ftEnd;
            }
            foreach (FIFPAppointment f in lsdList)
            {
                f.Start = new DateTime(f.Start.Year, f.Start.Month, f.Start.Day);
                f.End = new DateTime(f.End.Year, f.End.Month, f.End.Day);
            }*/

            calculation.ImportScenarioPlans = lsdList;
            calculation.InitUnitShutdownDictionary(calculation.ImportScenarioPlans); //This contains <unitId,List<FIFPAppointment>> dictionary collection 
            if (calculation.LayerUnitsDictionary.Count == 0)
                calculation.LayerUnitsDictionary = LayerUnitsDictionary;
            if (calculation.UnitCapacityDictionary.Count == 0)
                calculation.UnitCapacityDictionary = UnitCapacityDictionary;
            if (calculation.AllUnitList.Count == 0)
            {
                calculation.AllUnitList = UnitList;
                calculation.units_WaterModuleList = CalculationHelper.getWaterModules(UnitList);
                calculation.units_WIP = CalculationHelper.getWIP(UnitList);
                calculation.units_WaterStringList = CalculationHelper.getWaterStrings(UnitList);
                calculation.units_WaterRadialList = CalculationHelper.getWaterRadials(UnitList);
                calculation.units_GasCompressorList = CalculationHelper.getGasCompressors(UnitList);
                calculation.units_GasTowerList = CalculationHelper.getGasTowers(UnitList);
                calculation.units_GasAutoInjectionTowerList = CalculationHelper.getAutoInjectionTowers(UnitList);//UT-109,UT-250,UT-213
                calculation.units_GasRadialList = CalculationHelper.getGasPipelines(UnitList);//Since Changed unittype radial to pipeline in database need to do the corresponding changes here - Dhilip-18-05-2013
                calculation.units_OilStringList = CalculationHelper.getOilStrings(UnitList);
                calculation.units_OilRadialList = CalculationHelper.getOilRadials(UnitList);
                calculation.units_CP1 = CalculationHelper.getCP1(UnitList);
                calculation.units_USOSSP = CalculationHelper.getUSOSSP(UnitList);
                calculation.units_SeparatorList = CalculationHelper.getSeperators(UnitList);
                calculation.units_CSPSeparatorList = CalculationHelper.getCSPSeperators(UnitList);
                calculation.units_CSP1SeparatorList = CalculationHelper.getCSP1Seperators(UnitList);
                calculation.units_ByPass = CalculationHelper.getByPass(UnitList);
                if (FieldData != null)
                    calculation.FieldData = FieldData;
            }

            calculation.DefaultByPassRadialIdList = RadialSwitchDefaultValue.DefaultBypassRadialList;
            calculation.RadialSwitchList = MergeRadialSwitchDBWithTempList();
            calculation.ReducedCapacityList = GetCombinedRCList();
        }

        private List<EffectiveCapacityData> getRCData(DateTime startDayForRC, DateTime calculateEndDate)
        {
            List<EffectiveCapacityData> RCList = new List<EffectiveCapacityData>();
            while (startDayForRC <= calculateEndDate)
            {
                double currentMonthRC = calculation.CalculateCurrentMonthReservoirCapacity(startDayForRC);
                int numberOfDaysInCurrentMonth = DateTime.DaysInMonth(startDayForRC.Year, startDayForRC.Month);
                currentMonthRC = Math.Round(currentMonthRC / numberOfDaysInCurrentMonth, 2);
                RCList.Add(new EffectiveCapacityData() { Date = startDayForRC, EffectiveCapacity = (double.IsNaN(currentMonthRC)) ? 0 : currentMonthRC });
                //if (startDayForRC.Month == 12)
                //    break;
                startDayForRC = startDayForRC.AddMonths(1);
            }
            return RCList;
        }

        private List<EffectiveCapacityData> getOilData(DateTime startDayForEC, DateTime calculateEndDate)
        {
            List<EffectiveCapacityData> OilList = new List<EffectiveCapacityData>();
            int i = 0;
            double currentMonthTotalOilSumValue = 0;
            while (startDayForEC <= calculateEndDate)
            {
                double currentDayTotalOil = calculation.CalculateCurrentDayTotalOilCapacity(startDayForEC);
                int numberOfDaysInCurrentMonth = DateTime.DaysInMonth(startDayForEC.Year, startDayForEC.Month);
                currentMonthTotalOilSumValue += currentDayTotalOil;
                i++;
                if (i == numberOfDaysInCurrentMonth)
                {
                    currentMonthTotalOilSumValue = Math.Round(currentMonthTotalOilSumValue / numberOfDaysInCurrentMonth, 2);
                    OilList.Add(new EffectiveCapacityData() { Date = new DateTime(startDayForEC.Year, startDayForEC.Month, 1), EffectiveCapacity = (double.IsNaN(currentMonthTotalOilSumValue)) ? 0 : currentMonthTotalOilSumValue });
                    i = 0; currentMonthTotalOilSumValue = 0;
                }
                startDayForEC = startDayForEC.AddDays(1);
            }
            return OilList;
        }


        private List<EffectiveCapacityData> getECData(DateTime startDayForEC, DateTime calculateEndDate)
        {
            List<EffectiveCapacityData> ECList = new List<EffectiveCapacityData>();
            int i = 0;
            double currentMonthSumValue = 0;
            while (startDayForEC <= calculateEndDate)
            {
                double currentDayEC = calculation.CalculateCurrentDayEffectiveCapacity(startDayForEC);
                int numberOfDaysInCurrentMonth = DateTime.DaysInMonth(startDayForEC.Year, startDayForEC.Month);
                currentMonthSumValue += currentDayEC;
                i++;
                if (i == numberOfDaysInCurrentMonth)
                {
                    currentMonthSumValue = Math.Round(currentMonthSumValue / numberOfDaysInCurrentMonth, 2);
                    ECList.Add(new EffectiveCapacityData() { Date = new DateTime(startDayForEC.Year, startDayForEC.Month, 1), EffectiveCapacity = (double.IsNaN(currentMonthSumValue)) ? 0 : currentMonthSumValue });
                    i = 0; currentMonthSumValue = 0;
                }
                startDayForEC = startDayForEC.AddDays(1);
            }
            return ECList;
        }

        private void getLossData(DateTime startDayForLoss, DateTime calculateEndDate,
                                 List<LossByDivisionAndData> LOSSList, List<LossByDivisionAndData> allMonthlyLossList,
                                 List<EffectiveCapacityData> RCList, List<EffectiveCapacityData> ECList)
        {
            int il = 0;
            List<LossByDivisionAndData> currentMonthLossList = new List<LossByDivisionAndData>();
            List<LossByDivisionAndData> allLossList = new List<LossByDivisionAndData>();
            Dictionary<string, LossByDivisionAndData> reportLossDataDictionary = new Dictionary<string, LossByDivisionAndData>();
            while (startDayForLoss <= calculateEndDate)
            {
                List<LossByDivisionAndData> currentDayLossList = calculation.CalculateCurrentDayLossByDivision(startDayForLoss);
                int numberOfDaysInCurrentMonth = DateTime.DaysInMonth(startDayForLoss.Year, startDayForLoss.Month);

                currentMonthLossList.AddRange(currentDayLossList);
                allLossList.AddRange(currentDayLossList);
                il++;
                if (il == numberOfDaysInCurrentMonth)
                {
                    foreach (LossByDivisionAndData l in currentMonthLossList)
                    {
                        if (reportLossDataDictionary.ContainsKey(l.Division))
                        {
                            LossByDivisionAndData lossData = reportLossDataDictionary[l.Division];
                            lossData.Loss += l.Loss;
                        }
                        else
                        {
                            LossByDivisionAndData lossData = new LossByDivisionAndData();
                            lossData.Loss = l.Loss;
                            lossData.Division = l.Division;
                            lossData.Date = new DateTime(startDayForLoss.Year, startDayForLoss.Month, 1);
                            reportLossDataDictionary.Add(l.Division, lossData);
                        }
                    }
                    foreach (string division in reportLossDataDictionary.Keys.ToList<string>())
                    {
                        allMonthlyLossList.Add(new LossByDivisionAndData() { Division = division, Loss = Math.Round(reportLossDataDictionary[division].Loss, 2), Date = reportLossDataDictionary[division].Date });
                    }
                    il = 0;
                    currentMonthLossList.Clear();
                    reportLossDataDictionary.Clear();
                }
                startDayForLoss = startDayForLoss.AddDays(1);
            }

            /*
            //generate report data for loss
            Dictionary<string, LossByDivisionAndData> divisionLossDictionary = new Dictionary<string, LossByDivisionAndData>();
            foreach (LossByDivisionAndData l in allLossList)
            {
                if (divisionLossDictionary.ContainsKey(l.Division))
                {
                    LossByDivisionAndData reportLoss = divisionLossDictionary[l.Division];
                    reportLoss.Loss += l.Loss;
                }
                else
                {
                    LossByDivisionAndData reportLoss = new LossByDivisionAndData();
                    reportLoss.Loss = l.Loss;
                    reportLoss.Division = l.Division;
                    divisionLossDictionary.Add(l.Division, reportLoss);
                }
            }
            */

            //To calculate loss by Division - Dhilip 15-05-2013
            /*
            if (allMonthlyLossList != null && allMonthlyLossList.Count > 0)
            {
                List<LossByDivisionAndData> divisionLossList = (from item in allMonthlyLossList
                                                                group item by new { item.Division, item.Date.Year} into g
                                                                select new LossByDivisionAndData()
                                                                {
                                                                    Division = g.Key.Division,
                                                                    Loss = g.Sum(s => s.Loss),
                                                                    Date = new DateTime( g.Key.Year,1,1)
                                                                //{ Key = g.Key, Values = g.Sum(s => s.Loss) }).ToList<LossByDivisionAndData>();
                                                                }).ToList<LossByDivisionAndData>();

            }*/

            /*
            LOSSList.Add(new LossByDivisionAndData() { Division = "Res.C", Loss = Math.Round(RCList.Average(s => s.EffectiveCapacity), 2) });
            foreach (string division in divisionLossDictionary.Keys.ToList<string>())
            {
                LOSSList.Add(new LossByDivisionAndData() { Division = division, Loss = Math.Round(divisionLossDictionary[division].Loss / 12, 2) });
            }
            LOSSList.Add(new LossByDivisionAndData() { Division = "Eff.C", Loss = Math.Round(ECList.Average(s => s.EffectiveCapacity), 2) });
            */
        }

        private List<EffectiveCapacityData> getMCData(DateTime startDayForMC, DateTime calculateEndDate)
        {
            List<EffectiveCapacityData> MCList = new List<EffectiveCapacityData>();
            calculation.ImportScenarioPlans = new List<FIFPAppointment>();
            //calculation.InitUnitShutdownDictionary(calculation.ImportScenarioPlans); No need - Dhilip-18-05-2013
            calculation.UnitShutdownPlanDictionary = new Dictionary<int, List<FIFPAppointment>>();
            int j = 0;
            double currentMCMonthSumValue = 0;
            while (startDayForMC <= calculateEndDate)
            {
                double currentDayEC = calculation.CalculateCurrentDayEffectiveCapacity(startDayForMC);
                int numberOfDaysInCurrentMonth = DateTime.DaysInMonth(startDayForMC.Year, startDayForMC.Month);
                currentMCMonthSumValue += currentDayEC;
                j++;
                if (j == numberOfDaysInCurrentMonth)
                {
                    currentMCMonthSumValue = Math.Round(currentMCMonthSumValue / numberOfDaysInCurrentMonth, 2);
                    MCList.Add(new EffectiveCapacityData() { Date = new DateTime(startDayForMC.Year, startDayForMC.Month, 1), EffectiveCapacity = (double.IsNaN(currentMCMonthSumValue)) ? 0 : currentMCMonthSumValue });
                    j = 0; currentMCMonthSumValue = 0;
                }
                startDayForMC = startDayForMC.AddDays(1);
            }
            return MCList;
        }
        #endregion

        #region ImportVM_QueryForSaveCapacity_DataCompleted
        void ImportVM_QueryForSaveCapacity_DataCompleted(object sender, QueryForDataCompletedEventArgs e)
        {
            ServiceLocator.Get<MainPageVM>().IsLoading = false;
            ServiceLocator.Get<MainPageVM>().IsSaveButtonEnabled = true;
            ServiceLocator.Get<MainPageVM>().IsCalculateButtonEnabled = true;

            if (e.Result != null && e.Error == null)
            {
                if (e.UserState.ToString() == "SaveCapacityData")
                {
                    try
                    {
                        StringReader reader = new StringReader(e.Result.Any1.ToString());
                        XmlReader xmlR = XmlReader.Create(reader);

                        XDocument doc = XDocument.Load(xmlR);
                        if (doc != null)
                        {
                            //int retValue = Convert.ToInt32(doc.Descendants("Query").Elements("retValue").FirstOrDefault());
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
            else
            {
                ServiceLocator.Get<MainPageVM>().IsLoading = false;
                MessageBox.Show("Database connection error while saving the calculation data.");
            }
        }
        #endregion

        #region SerializeObject
        private string SerializeObject(ReportData toSerialize)
        {
            XmlSerializer xsSubmit = new XmlSerializer(toSerialize.GetType());
            StringWriter sww = new StringWriter();
            XmlWriter writer = XmlWriter.Create(sww);
            xsSubmit.Serialize(writer, toSerialize);
            return sww.ToString();
        }
        #endregion

        #region BindScenarioToScheduleView
        private void BindScenarioToScheduleView(List<FIFPAppointment> baseScenarioList)
        {
            AppointmentGroup appointmentGroup = new AppointmentGroup();
            List<ResourceType> lstResources = new List<ResourceType>();
            List<Resource> unitList = new List<Resource>();
            ResourceType unitType = new ResourceType("Unit");
            unitType.DisplayName = "Unit";
            unitType.Name = "Unit";
            foreach (FIFPAppointment appointment in baseScenarioList)
            {
                Resource resource = new Resource() { ResourceName = appointment.UnitName, DisplayName = appointment.UnitName, ResourceType = unitType.Name };
                if (!unitList.Contains(resource))
                    unitList.Add(resource);
                appointment.Resources.Add(resource);
            }

            appointmentGroup.Appointments = baseScenarioList;
            unitType.Resources.AddRange(unitList);
            lstResources.Add(unitType);


            appointmentGroup.ResourceTypes = lstResources;
            appointmentGroup.UnitList = unitList;

            if (OnAppointmentDataCompleted != null)
                OnAppointmentDataCompleted(this, new CustomEventArgs<AppointmentGroup>(appointmentGroup));
        }
        #endregion

        #region ShowPopup
        private void ShowPopup(string title, string message)
        {
            Warning warningWindow = new Warning();
            warningWindow.CancelButton.Visibility = Visibility.Collapsed;
            warningWindow.Title = string.Format(title);
            warningWindow.lblMessage.Text = string.Format(message);
            warningWindow.lblMessage.Visibility = Visibility.Visible;
            warningWindow.Show();
            warningWindow.OKButton.Click += (o, e1) =>
            {
                warningWindow.lblMessage.Visibility = Visibility.Collapsed;
            };
        }
        #endregion

        #region ShowNoBaseScenarioMessage
        private void ShowNoBaseScenarioMessage()
        {
            ShowPopup(FIFPConstants.WARNINGTITLE_BASE_NO, FIFPConstants.WARNINGMESSAGE_BASE_NO);
        }
        #endregion

        #region HidePopup
        private void HidePopup(Button btnCancel)
        {
            ResetFields();
        }

        private void ResetFields()
        {
            _validationResults.Clear();
            ScenarioName = string.Empty;
            if (scenarioPopup != null)
                scenarioPopup.Close();

            if (ecPopup != null)
                ecPopup.Close();
            if (activityPopup != null)
            {
                IsAddActivityButtonEnabled = true;
                activityPopup.Close();
            }
            if (DivisionCodeList.Count > 0)
                SelectedDivisionName = DivisionCodeList[0];
            //if (ActivityCodeList.Count > 0)
            //    SelectedActivityCode = ActivityCodeList[0];
            if (UnitTypeList.Count > 0)
            {
                SelectedUnitType = UnitTypeList[0];
                SettingsSelectedUnitType = UnitTypeList[0];
            }

            if (LayerList.Count > 0)
            {
                SelectedLayer = LayerList[0];
                SelectedMaxProdLayer = LayerList[0];
            }

            NewUnplannedLossesPercentage = string.Empty;
            NewMonitoringPercentage = string.Empty;
            NewCapacity = string.Empty;
            NewIPR = string.Empty;
            NewMaxProduction = string.Empty;
            BPercentageValidate = false;
            //if (UnitNameList.Count > 0)
            //    SelectedActivityUnit = UnitNameList[0];
        }
        #endregion

        #region ShowPopup
        private void ShowPopup(Button btnShow)
        {
            SaveAsNewScenario();
        }

        private void SaveAsNewScenario()
        {
            IsScenarioExist = false;
            if (CheckValidation())
            {
                if (SelectedECPlan == FIFPConstants.EC_NEWSCENARIO)
                    SaveAsScenario(ScenarioName, "EC", "SaveAsNewScenario");
                else
                    SaveAsScenario(ScenarioName, "USC", "SaveAsNewScenario");
            }
        }
        #endregion

        #region Load Textbox
        TextBox txtScenarioName = null;
        private void LoadScenarioNameTextBox(TextBox txtBox)
        {
            txtScenarioName = txtBox;
        }
        #endregion

        private void UpdateScenarioNameByKeyPress(object e)
        {
            KeyEventArgs args = e as KeyEventArgs;
            if (args != null && args.Key == Key.Enter)
            {
                ScenarioName = txtScenarioName.Text;
                SaveAsNewScenario();
            }
        }

        #region CheckValidation
        private bool CheckValidation()
        {
            bool bRet = true;

            if (string.IsNullOrEmpty(ScenarioName))
            {
                bRet = false;
                IsScenarioExist = false;
                txtScenarioName.Focus();
                NotifyPropertyChanged(() => ScenarioName);
            }
            else if (!string.IsNullOrEmpty(ScenarioName) && ScenarioList.Where(s => s.ScenarioName.Contains(ScenarioName)).FirstOrDefault() != null)
            {
                bRet = false;
                IsScenarioExist = true;
                txtScenarioName.Focus();
                NotifyPropertyChanged(() => ScenarioName);
            }
            else
            {
                bRet = true;
                IsScenarioExist = false;
                NotifyPropertyChanged(() => ScenarioName);
            }
            return bRet;
        }
        #endregion

        #region Filter with all criteria
        private void DoFilterButtonVisibility(RadioButton rdFilter)
        {
            _validationResults.Clear();
            UnitName = string.Empty;
            IsUnitNameExist = false;

            if (IsAnimationStarted)
            {
                IsAnimationStarted = false;
                StoryboardManager.PlayStoryboard(FIFPConstants.SETTINGSFLIP_STOP, s => { }, null);
            }
            string filterType = string.Empty;
            if (rdFilter != null && rdFilter.Tag != null)
                filterType = Convert.ToString(rdFilter.Tag);

            //if (FilterTreeVisibility == Visibility.Visible)
            //    BindScenarioToScheduleView((from item in ImportPlans orderby item.nIndex ascending select item).ToList<FIFPAppointment>());

            if (!string.IsNullOrEmpty(filterType))
            {
                switch (filterType)
                {
                    case "filter":
                        FilterVisibility = FilterVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
                        FilterTreeVisibility = Visibility.Collapsed;
                        IsUnitFilterVisibility = FilterVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
                        break;
                    case "filtertree":
                        FilterVisibility = Visibility.Collapsed;
                        IsUnitFilterVisibility = Visibility.Visible;
                        FilterTreeVisibility = FilterTreeVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
                        break;
                }

            }
        }
        #endregion

        #region Filter with unit name
        private void FilterByUnitName(Button rdFilter)
        {
            SearchByUnitName();
        }

        private void SearchByUnitName()
        {
            if (!string.IsNullOrEmpty(UnitName))
            {
                if (CheckUnitNameValidation())
                {
                    IsUnitNameExist = false;
                    NotifyPropertyChanged(() => UnitName);
                    if (ImportPlans != null && ImportPlans.Count > 0)
                    {
                        List<FIFPAppointment> lstAppointments = (from item in ImportPlans
                                                                 where item.UnitName.ToLower() == UnitName.ToLower()
                                                                 orderby item.nIndex ascending
                                                                 select item).ToList<FIFPAppointment>();
                        BindScenarioToScheduleView(lstAppointments);
                    }
                }
            }
            else
            {
                IsUnitNameExist = false;
                NotifyPropertyChanged(() => UnitName);
                BindScenarioToScheduleView((from item in ImportPlans orderby item.nIndex ascending select item).ToList<FIFPAppointment>());
            }
        }
        #endregion

        #region CheckUnitNameValidation
        private bool CheckUnitNameValidation()
        {
            bool bRet = true;

            //if (string.IsNullOrEmpty(UnitName))
            //{
            //    bRet = false;
            //    IsUnitNameExist = false;
            //    NotifyPropertyChanged(() => UnitName);
            //}
            if (!string.IsNullOrEmpty(UnitName) && ImportPlans.Where(s => s.UnitName.ToLower().Equals(UnitName.ToLower())).FirstOrDefault() == null)
            {
                bRet = false;
                IsUnitNameExist = true;
                NotifyPropertyChanged(() => UnitName);
            }
            //else
            //{
            //    bRet = true;
            //    IsUnitNameExist = false;
            //    NotifyPropertyChanged(() => UnitName);
            //}
            return bRet;
        }
        #endregion

        #region DoValidation
        private bool DoDateValidation()
        {
            bool bRet = true;

            if (ActivityStartDate > ActivityEndDate)
            {
                bRet = false;
                NotifyPropertyChanged(() => ActivityStartDate);
            }
            else if (ActivityEndDate < ActivityStartDate)
            {
                bRet = false;
                NotifyPropertyChanged(() => ActivityEndDate);
            }
            else
            {
                NotifyPropertyChanged(() => ActivityStartDate);
                NotifyPropertyChanged(() => ActivityEndDate);
            }

            return bRet;
        }
        #endregion

        #region Load Textbox
        TextBox txtUnitName = null;
        private void LoadTextBox(TextBox txtBox)
        {
            txtUnitName = txtBox;
        }
        #endregion

        #region UnitTextBoxKeyDown
        private void UnitTextBoxKeyDown(object e)
        {
            //txtUnitName.Focus();
            //txtUnitName.SelectionStart = txtUnitName.Text.Length;            
            KeyEventArgs args = e as KeyEventArgs;
            if (args != null && args.Key == Key.Enter)
            {
                UnitName = txtUnitName.Text.Trim();
                SearchByUnitName();
            }
        }
        #endregion

        #region StartDate_SelectedDateChanged
        private void StartDate_SelectedDateChanged(DatePicker datePicker)
        {
            if (FromDate.SelectedDate != null)
            {
                if (ActivityEndDate != null)
                {
                    //if (ActivityEndDate < ActivityStartDate)
                    //    ActivityEndDate = null;
                }
                this.ToDate.BlackoutDates.Clear();
                this.ToDate.BlackoutDates.Add(new CalendarDateRange(new DateTime(), ((DateTime)this.FromDate.SelectedDate).AddDays(-1)));
            }
        }
        #endregion

        #region Load Start Date
        DatePicker FromDate = new DatePicker();
        private void LoadStartDate(DatePicker startDatePicker)
        {
            FromDate = startDatePicker;
            FromDate.SelectedDate = DateTime.Now;
            FromDate.BlackoutDates.Add((new CalendarDateRange(new DateTime(), Convert.ToDateTime(ActivityStartDate).AddDays(-1))));
        }
        #endregion

        #region LoadEndDate
        DatePicker ToDate = new DatePicker();
        private void LoadEndDate(DatePicker endDatePicker)
        {
            ToDate = endDatePicker;
            ToDate.SelectedDate = DateTime.Now.AddDays(1);
            ToDate.BlackoutDates.Add((new CalendarDateRange(new DateTime(), Convert.ToDateTime(ActivityStartDate).AddDays(-1))));
        }
        #endregion

        #region Validation
        protected void NotifyPropertyChanged(Expression<Func<object>> propertyExpression)
        {
            if (propertyExpression == null)
                throw new ArgumentNullException(FIFPConstants.propertyExpression);

            var propertyName = GetPropertyName(propertyExpression);
            OnPropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            Validate(propertyName);
            OnNotifyPropertyChanged();
        }

        protected virtual void OnNotifyPropertyChanged() { }

        private string GetPropertyName(Expression<Func<object>> propertyExpression)
        {
            var unaryExpression = propertyExpression.Body as UnaryExpression;
            var memberExpression = unaryExpression == null ? (MemberExpression)propertyExpression.Body : (MemberExpression)unaryExpression.Operand;

            var propertyName = memberExpression.Member.Name;

            return propertyName;
        }


        private void NotifyErrorsChanged(string propertyName)
        {
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
        }

        protected void Validate(string propertyName)
        {
            var value = GetPropertyValue(propertyName);
            RemoveErrorsForProperty(propertyName);
            Validator.TryValidateProperty(value, new ValidationContext(this, null, null) { MemberName = propertyName }, _validationResults);
            NotifyErrorsChanged(propertyName);
        }

        protected void Validate()
        {
            _validationResults.Clear();
            Validator.TryValidateObject(this, new ValidationContext(this, null, null), _validationResults, true);

            foreach (var result in _validationResults)
                NotifyErrorsChanged(result.MemberNames.First());

        }

        private object GetPropertyValue(string propertyName)
        {
            var type = this.GetType();

            var propertyInfo = type.GetProperty(propertyName);

            if (propertyInfo == null)
            {
                throw new ArgumentException(string.Format(FIFPConstants.Couldntfindanyproperty, propertyName, type));
            }

            return propertyInfo.GetValue(this, null);
        }

        private void RemoveErrorsForProperty(string propertyName)
        {
            var validationResults = _validationResults.Where(result => result.MemberNames.Contains(propertyName)).ToList();

            foreach (var result in validationResults)
                _validationResults.Remove(result);
        }

        public IEnumerable GetErrors(string propertyName)
        {
            return _validationResults.Where(result => result.MemberNames.Contains(propertyName));
        }

        public bool HasErrors
        {
            get { return _validationResults.Any(); }
        }

        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        //public event PropertyChangedEventHandler PropertyChanged;
        #endregion


    }
}
